【问题标题】:Image in flexbox column not rendering properly in Chromeflexbox 列中的图像无法在 Chrome 中正确呈现
【发布时间】:2019-05-28 02:07:21
【问题描述】:

我有一个 div,其中包含一个图像和一个段落。

<div id="container">
  <img src="..." />
  <p>
    This is my text
  </p>
</div>

我使用 flex-box 和 flex-direction: column 来对齐它们。

#container {
  display: flex;
  flex-direction: column;
  height: 300px;
  width: 400px;
}

img {
  max-width: 80%;
  flex-basis: 50%;
}

p {
  flex-basis: 50%;
}

由于imgp 都有flex-basis 50%,我希望它们每个都占用50% 的空间。在 Firefox 中它可以工作,但在 Chrome 中,图像比容器本身更大(高度)。

我制作了一个 jsfiddle 来证明这一点:https://jsfiddle.net/q2esvro9/1/

如何在 Chrome 中获取 Firefox 的行为?

(另一个有趣的事实:在 Internet Explorer 11 中,图像和文本占据了相同的空间,但图像的宽度被拉伸了。这意味着对于非常短且简单的 CSS 代码有 3 种不同的行为)

#container {
  display: flex;
  align-items: center;
  align-content: center;
  text-align: center;
  flex-direction: column;
  border: solid 2px red;
  height: 300px;
  width: 400px;
}

img {
  max-width: 80%;
  flex-basis: 50%;
}

p {
  flex-basis: 50%;
  border: solid 2px green;
}
<div id="container">
  <img src="https://image.freepik.com/free-icon/apple-logo_318-40184.jpg" />
  <p>
    This is my text
  </p>
</div>

【问题讨论】:

  • 不知道为什么浏览器会在这里发生不同的事情,但你可以为我想的 img css 添加max-height: 50%
  • min-height:0 图片将解决此问题
  • 但它破坏了纵横比(在 Chrome 上)。
  • 在我看来并不完全重复,因为这里的解决方案是一个两步过程。副本仅涵盖一个。

标签: css google-chrome firefox flexbox


【解决方案1】:

主要浏览器之间存在 flexbox 渲染变化。

在处理图像时,变化的数量会增加。

我发现跨浏览器的一致工作是flex formatting context 中使用img 元素(即,不要让它们成为弹性项目)。

相反,将img 包装在 div 元素中,使 div 成为弹性项目并将图像保存在 block formatting context 中。

#container {
  display: flex;
  align-items: center;
  align-content: center;
  text-align: center;
  flex-direction: column;
  border: solid 2px red;
  height: 300px;
  width: 400px;
}

#container > div {
  flex: 0 0 50%;  /* 1 */
  min-height: 0;  /* 2 */
}

img {
  height: 100%;
}

p {
  flex-basis: 50%;
  border: solid 2px green;
}
<div id="container">
  <div>
    <img src="https://image.freepik.com/free-icon/apple-logo_318-40184.jpg" />
  </div>
  <p>
    This is my text
  </p>
</div>

注意事项:

  1. The meaning and benefits of flex: 1
  2. Why don't flex items shrink past content size?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-12
    • 2020-05-02
    • 2012-09-13
    • 2020-01-10
    • 2012-05-22
    • 2018-02-27
    • 2019-08-18
    相关资源
    最近更新 更多