[英]Image inside flex-item ignores max-height:100% in chrome and firefox - (works in safari)
I want an image to fill either the width or height of the window-size/viewport. 我想要一个图像来填充窗口大小/视口的宽度或高度。
For a better understanding of what i'm trying to do, i've created an example on codepen - please check out and resize the preview. 为了更好地理解我正在尝试做什么, 我在codepen上创建了一个示例 - 请检查并调整预览大小。 It works fine in safari but chrome and firefox seems to have problems.
它在safari中运行良好,但chrome和firefox似乎有问题。 The image ignores the max-height property and overflows the flex-item dimensions.
图像忽略max-height属性并溢出flex-item维度。
Any suggestions to get this work in chrome and firefox? 有任何建议让你的工作在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="http://i.stack.imgur.com/mrEyQ.jpg"> </div> </div>
The problem is that both the image and its containing block have 问题是图像及其包含块都有
max-height: 100%;
Instead, remove the max
for the containing block: 而是删除包含块的
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="http://i.stack.imgur.com/mrEyQ.jpg"> </div> </div>
However, note that .flex-item
will be centered inside .flex-container
, but the image won't be centered inside .flex-item
. 但是,请注意
.flex-item
将在.flex-container
内.flex-container
,但图像不会在.flex-item
内.flex-item
。
To fix that, you can use the centering in the unknown technique (or alternatively, flexbox). 要解决这个问题,您可以使用未知技术(或者Flexbox)的居中。
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="http://i.stack.imgur.com/mrEyQ.jpg"> </div> </div>
In Orio's solution the image is not vertical aligned in Safari, if the flex container' width is smaller than the width of the image: Safari Screenshot 在Orio的解决方案中,如果Flex容器的宽度小于图像的宽度,则图像在Safari中不是垂直对齐的: Safari屏幕截图
If I add 如果我加
/* Safari 7.1+ only */
_::-webkit-full-page-media, _:future, :root .flex-item { height : auto; }
to the css the image is vertical centered in Safari. 对于CSS,图像在Safari中是垂直居中的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.