html - flex-grow 不适用于图像

标签 html css flexbox flex-grow

目前,我正在尝试列一个 list 。在适合我的“显示 flex 布局”并在所有浏览器上调整大小的左侧图像。我的“flex 增长布局”列表 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>

谢谢

西蒙

最佳答案

你有图像容器—— flex 元素div——设置为flex-grow: 1。没关系。

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

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

将此添加到您的代码中:

  • flex 基础:0

或者,更好的是,这个:

  • flex: 1

这是以下内容的缩写:

  • flex: 1 1 0

这是以下内容的缩写:

  • flex 增长:1
  • flex-shrink: 1
  • flex 基础: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 之间区别的解释,请参阅此帖子:

#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>

关于html - flex-grow 不适用于图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47395307/

相关文章:

php - 如何在浏览器中存储缓存?

javascript - JWPlayer 自动检测每个用户的最佳质量,而不使用其他浏览器的 flash 播放器(HLS、.m3u8)?

html - 宽度 100% 的表格未填充父级 <div>

html - 带显示的div : flex is not centering child div

html - Internet Explorer 11 flex 盒问题

javascript - 在 HTML 中嵌入 jquery.tablesorter.widgets.js

javascript - 在文本替换 javascript 中使用正则表达式

css - 如果容器 div 较小,如何将子 div 扩展到 100% 屏幕宽度?

javascript - 需要显示篮球的前三个字母,然后是点

css - 具有显示 flex 及其子高度的等高列(以百分比表示)