下面的 fiddle 有三个方块。

块1 包含三列。中间的列中有两行,每行设置为flex:1。

块2 包含三列。中间的列中有两行,每行设置为flex:1。第二行包含一条狗的图像。图像将不会缩小到包含图像的行的高度。

块3 仅包含中间的列,中间有两行,每行设置为flex:1。第二行包含一条狗的图像。图像确实缩小到包含图像的行的高度。

问题是,为什么块2中间列的第二行中的图像不缩小到包含该行的行的高度?我可以添加哪些CSS规则来实现这一目标?

.block{
    height:100px;
}

.wrapper{
    border:5px solid purple;
    display:flex;
    flex-direction:row;
}

.column{
    flex:1;
    border:3px solid yellow;
}

.middle{
    display:flex;
    flex-direction:column;
}

.first{
    background:red;
}

.second{
    background:orange;
}

.third{
    background:purple;
}

.row{
    flex:1;
    border:1px solid black;
    display:flex;
    align-items:stretch;
}

img{
    flex:1;
}
<div class="wrapper block">
<div class="left column"></div>
<div class="middle column">
  <div class="row first"></div>
  <div class="row second"></div>

</div>
<div class="right column"></div>
</div>

<div class="wrapper block">
<div class="left column"></div>
<div class="middle column">
  <div class="row first"></div>
  <div class="row second">
            	<img src="https://upload.wikimedia.org/wikipedia/commons/8/89/Dog.svg" />
  </div>

</div>
<div class="right column"></div>
</div>

<div class="middle block">
  <div class="row first"></div>
  <div class="row second">
            	<img src="https://upload.wikimedia.org/wikipedia/commons/8/89/Dog.svg" />
  </div>

</div>

最佳答案

解决方案

代替:

.row {
    flex: 1;
    border: 1px solid black;
    display: flex;
    align-items: stretch;
}

和:
.row {
    flex: 1 1 0px;             /* adjustment on this line */
    border: 1px solid black;   /* no change */
    display: flex;             /* no change */
    align-items: stretch;      /* no change */
}

DEMO 1

解释

你写了:



看来您只在Chrome中测试了代码,因为当涉及到Firefox和IE11时,问题的前提是错误的。

在那些浏览器中,第二块中的狗的图像很好地包含在flex元素中。图像在IE中有些拉伸(stretch),但是仍然包含在内。

您的问题似乎与Chrome有关。 (我没有在Safari中进行测试,但这是一个WebKit浏览器,例如Chrome,因此解决方案可能相似。)

如果您想跨浏览器进行测试,这是原始代码的演示:

DEMO 2

这个问题的解决方案很有趣,因为属性值的微小差异(似乎微不足道)使Chrome渲染功能产生了很大差异。

您的图像是div.row的子元素(更具体而言:flex项),div.row是具有行方向的flex容器。
flex: 1还是较大容器的 flex 元素(沿列方向),并已应用flex: 1。 Chrome中的问题根源于该flex: 1声明。
flex是什么意思?
flex-grow属性是 flex-shrink flex-basis flex: 1 的简写。

flex-grow: 1 等效于flex-shrink: 1flex-basis: 0%0

注意flex之后的百分号(%)。它是在flexbox规范的Common Values of flex: 1 中定义的,实际上有所不同。

在Chrome中尝试以下操作:

用等效的div.row替换flex: 1 1 0%中的flex: 1 1 0px。您会注意到渲染时没有任何变化。

现在删除百分号并再次运行。图像捕捉到位。

CSS-Tricks中所述,将其设置为px也可以。

DEMO 3

因此,在0上使用px或不使用单位(而不是百分比)可以解决Chrome中的问题...并且在Firefox中不会破坏任何内容。

但是,在IE11中,ojit_code有效,但无单位无效。实际上,无单元消除了布局。

但是IE11是另一个故事...

IE11在浏览器支持数据网站caniuse.com上一直显示对flexbox的完全支持,直到最近,由于“存在大量错误”,该浏览器降级为部分支持。在测试上面的演示时,IE11定期刷新时呈现相同的代码。有关问题列表,请参见caniuse.com上的Known Issues选项卡。

请注意,所有主要的浏览器except IE 8 & 9都支持flexbox。某些最新的浏览器版本(例如Safari 8和IE10)需要vendor prefixes。如上所述,由于一些已知的错误,IE11提供了部分支持。要快速添加所需的所有前缀,请使用Autoprefixerthis answer中的更多浏览器兼容性详细信息。

关于html - flexbox中的图像行为(行中嵌入行),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33975539/

10-13 01:51
查看更多