flex-item中的图像忽略了最大高度:chrome和firefox中的100% - (在safari中工作)

时间:2015-05-05 14:48:17

标签: css css3 flexbox

我希望图像填充窗口大小/视口的宽度或高度。

为了更好地理解我正在尝试做的事情i’ve created an example on codepen - 请检查并调整预览的大小。 它在safari中运行良好但是chrome和firefox似乎有问题。图像忽略max-height属性并溢出flex-item维度。

有什么建议可以在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>

2 个答案:

答案 0 :(得分:4)

问题是图像及其包含块都有

max-height: 100%;

而是删除包含块的max

.flex-item {
    width: 100%;
    height: 100%;
}

&#13;
&#13;
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%;
}
&#13;
<div class="flex-container">
  <div class="flex-item">
    <img src="http://i.stack.imgur.com/mrEyQ.jpg">
  </div>
</div>
&#13;
&#13;
&#13;

但请注意,.flex-item将位于.flex-container内,但图片不会位于.flex-item内。

要解决此问题,您可以使用centering in the unknown技术(或者Flexbox)。

&#13;
&#13;
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;
}
&#13;
<div class="flex-container">
  <div class="flex-item">
    <img src="http://i.stack.imgur.com/mrEyQ.jpg">
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

在Orio的解决方案中,如果Flex容器的宽度小于图像的宽度,则图像在Safari中不是垂直对齐的:Safari Screenshot

如果我添加

/*  Safari 7.1+ only */
_::-webkit-full-page-media, _:future, :root .flex-item  { height : auto; }

到css,图像在Safari中垂直居中。

JSFiddle

相关问题