【问题标题】:Image inside flex-item ignores max-height:100% in chrome and firefox - (works in safari)flex-item 中的图像在 chrome 和 firefox 中忽略 max-height:100% - (在 safari 中有效)
【发布时间】:2015-07-15 09:09:04
【问题描述】:

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

为了更好地了解我想要做什么,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>

【问题讨论】:

    标签: css flexbox


    【解决方案1】:

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

    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="http://i.stack.imgur.com/mrEyQ.jpg">
      </div>
    </div>

    但是,请注意.flex-item 将在.flex-container 内部居中,但图像不会在.flex-item 内部居中。

    要解决这个问题,您可以使用centering in the unknown 技术(或者,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>

    【讨论】:

    • 我找到的关于这个主题的最佳答案。
    • 谢谢你!我遇到了类似的问题,嵌套 div 不尊重 Chrome 中的最大高度,而 Safari 工作正常
    【解决方案2】:

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

    如果我添加

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

    对于 css,图像在 Safari 中垂直居中。

    JSFiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      • 2012-10-19
      • 2022-08-04
      • 1970-01-01
      • 2021-10-29
      • 1970-01-01
      • 2014-05-07
      相关资源
      最近更新 更多