flex-grow 不适用于图像

flex-grow is not working with images

目前,我正在尝试列一个清单。在适合我的 "display flex layout" 并在所有浏览器上调整大小的左侧图像。我的 "flex-grow layout" 列表 1 用于图像,3 用于描述。没有图像,一切都很好,但是对于我的图像(100% 宽度),它不适合行的 1/3 ...

有人知道解决办法吗?

#main {
    height: 100px;
    border: 1px solid #c3c3c3;
    display: -webkit-flex; /* Safari */
    display: flex;
}
#main div:nth-of-type(1) {-webkit-flex-grow: 1;}
#main div:nth-of-type(2) {-webkit-flex-grow: 3;}
#main div:nth-of-type(1) {flex-grow: 1;}
#main div:nth-of-type(2) {flex-grow: 3;}
#main img { width: 100% }
<div id="main">
  <div style="background-color:coral;"><img src="http://www.der-eyecatcher.de/wp-content/uploads/2016/02/Lampe-silber-Schirm_1.jpg"></div>
  <div style="background-color:lightblue;">Description</div>
</div>

<hr>flex-grow without Image<hr>

<div id="main">
  <div style="background-color:coral;"></div>
  <div style="background-color:lightblue;">Description</div>
</div>

谢谢

西蒙

您已将图像容器 – 弹性项目 div – 设置为 flex-grow: 1。没关系。

除了 flex-basis 的默认值是 auto (spec)。

因此,您是在告诉项目它的初始主要尺寸(即 flex-basis)应该是其内容(图像)的尺寸。这正是正在发生的事情。该项目采用图像的自然尺寸。

将此添加到您的代码中:

  • flex-basis: 0

或者,更好的是,这个:

  • flex: 1

这是以下简称:

  • flex: 1 1 0

这是以下简称:

  • flex-grow: 1
  • flex-shrink: 1
  • flex-basis: 0

来自规范:

7.2. Components of Flexibility

Authors are encouraged to control flexibility using the flex shorthand rather than with its longhand properties directly, as the shorthand correctly resets any unspecified components to accommodate common uses.

有关 flex-basis: autoflex-basis: 0 之间区别的解释,请参阅此 post:

#main {
  height: 100px;
  border: 1px solid #c3c3c3;
  display: flex;
}

/* adjustment here */
#main div:nth-of-type(1) {
  flex: 1;
}

#main div:nth-of-type(2) {
  flex-grow: 3;
}

#main img {
  width: 100%;
  height: auto;
}
<div id="main">
  <div style="background-color:coral;"><img src="http://www.der-eyecatcher.de/wp-content/uploads/2016/02/Lampe-silber-Schirm_1.jpg"></div>
  <div style="background-color:lightblue;">Description</div>
</div>

<hr>flex-grow without Image
<hr>

<div id="main">
  <div style="background-color:coral;"></div>
  <div style="background-color:lightblue;">Description</div>
</div>