Image height inside flexbox not working in Chrome

好久不见. 提交于 2019-12-05 13:52:33
Michael_B

There are two problems you need to overcome:

Firefox solves them both on its own, but Chrome needs assistance.

Problem #1

The first problem is that flex items, by default, cannot be smaller than their content. An initial setting on flex items is min-height: auto.

Therefore, a flex item with a replaced element, like an image, will default to the inherent size of the image. The item cannot be made smaller, unless you override the initial setting (use min-height: 0).

#flex-container {
  height: 300px;
  width: 500px;
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  align-items: center;
  border: 5px solid black;
}
#container1, #container2 {
  height: 100px;
  width: 300px;
  background: orange;
  flex: 1 0 auto;
}
img { min-height: 0; } /* NEW */
<div id="flex-container">

  <div id="container1">300x100 px</div>

  <img src="http://i.imgur.com/RRUe0Mo.png" alt="">

  <div id="container2">300x100 px</div>

</div>

A complete explanation of this issue can be found here:


Problem #2

Then you hit the second problem: keeping the aspect ratio. This is a common problem in flex containers. One option is to define a height for the image:

#flex-container {
  height: 300px;
  width: 500px;
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  align-items: center;
  border: 5px solid black;
}
#container1, #container2 {
  height: 100px;
  width: 300px;
  background: orange;
  flex: 1 0 auto;
}
img { min-height: 0; height: 100px; } /* NEW */
<div id="flex-container">

  <div id="container1">300x100 px</div>

  <img src="http://i.imgur.com/RRUe0Mo.png" alt="">

  <div id="container2">300x100 px</div>

</div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!