css - Flexbox 列中的图像无法在 Chrome 中正确呈现

标签 css google-chrome firefox flexbox

我有一个包含一张图片和一个段落的 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 中,图像和文本占用相同的空间,但图像的宽度被拉伸(stretch)了。这意味着非常短且简单的 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>

最佳答案

主要浏览器之间存在 flexbox 渲染差异。

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

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

相反,将 img 包装在 div 元素中,使 div 成为 flex 元素并将图像保存在 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?

关于css - Flexbox 列中的图像无法在 Chrome 中正确呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53989183/

相关文章:

javascript - 在 Firefox 中,设置 checkbox.disabled = false 后 click() 不会立即运行

javascript - 使用 setTimeouts 排队的浏览器功能可以自动放弃吗?

javascript - 插入符号图标不想位于菜单项旁边

html - 我如何并排放置3张 table

HTML 5 输入类型 ='date' 禁用键盘输入

iis - Chrome 是否忽略缓存控制 : max-age?

html - 极其简单的 flexbox 布局,溢出 : hidden -- vertical mis-alignment in Firefox

css - 在 Firefox 中显示 Arial Black 有技巧吗?

css - 试图在悬停时嵌套 css 选择器

html - 如何在保持所有区域可点击的同时使不规则形状的 SVG 重叠?