我想要一个图像填充窗口大小/视口的宽度或高度。
为了更好的理解我正在尝试做的事情,我在 codepen 上创建了一个示例 http://codepen.io/durchgemacht/pen/WvQvZJ- 请查看并调整预览大小。它在 safari 中运行良好但是chrome和firefox好像有问题。图像忽略 max-height 属性并溢出弹性项目尺寸。
有什么建议可以在 Chrome 和 Firefox 中实现此功能吗?
html,
body {
height: 100%;
}
.flex-container {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
background: green;
}
.flex-item {
max-width: 100%;
max-height: 100%;
}
img {
max-width: 100%;
max-height: 100%;
}
<div class="flex-container">
<div class="flex-item">
<img src="https://i.stack.imgur.com/mrEyQ.jpg">
</div>
</div>
问题是图像及其包含块都有
max-height: 100%;
相反,删除max
对于包含块:
.flex-item {
width: 100%;
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
}
.flex-container {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
background: green;
}
.flex-item {
width: 100%;
height: 100%;
}
img {
max-width: 100%;
max-height: 100%;
}
<div class="flex-container">
<div class="flex-item">
<img src="https://i.stack.imgur.com/mrEyQ.jpg">
</div>
</div>
但请注意.flex-item
将在内部居中.flex-container
,但图像不会在内部居中.flex-item
.
要解决这个问题,您可以使用以未知为中心 https://css-tricks.com/centering-in-the-unknown/技术(或者弹性盒)。
html,
body {
height: 100%;
margin: 0;
}
.flex-container {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
background: green;
}
.flex-item {
width: 100%;
height: 100%;
text-align: center;
}
.flex-item:after {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
img {
max-width: 100%;
max-height: 100%;
vertical-align: middle;
}
<div class="flex-container">
<div class="flex-item">
<img src="https://i.stack.imgur.com/mrEyQ.jpg">
</div>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)