我已经阅读了所有现有的解决方案,其中图像可以填充包含的 div,但我还没有找到填充没有静态尺寸的 div 的解决方案,例如仅由 flex 布局的 div -成长
。
目前图像会破坏我在容器上设置的 flex-grow
比例。我希望 img
只填充 div 而不是拉伸(stretch) div。
尽量不要内联样式。
是否有现成的 polyfill 或解决方案?
.container {
display: flex;
min-height: 300px;
width: 500px;
flex: 1;
}
.sub-container {
flex: 1;
display: flex;
flex-direction: row;
}
.sub-container > div {
flex-grow: 1;
}
.first-container {
background-color: blue;
}
.second-container {
background-color: yellow;
}
.second-container>img {
max-height: 100%;
max-width: 100%;
object-fit: scale-down;
}
<div class="container">
<div class="sub-container">
<div class="first-container">
A
</div>
<div class="second-container">
<img src="https://internationalbarcodes.net/wp-content/uploads/2017/04/QR%20code%20example.jpg" />
</div>
</div>
</div>
最佳答案
你的代码中有这个:
.sub-container > div {
flex-grow: 1;
}
好的,这定义了 flex-grow
。
但是你还没有定义flex-basis
.因此,flex-basis
保留其默认值,即:auto
(i.e., content-defined) .
这就是您所看到的布局:一个根据内容调整大小的 flex 元素。
换句话说,因为图像的自然尺寸太大(与容器的大小相比),图像占用了所有可用空间,flex-grow
没有效果(它没有可分配的可用空间)。
作为解决方案,将此添加到规则中:
.sub-container > div {
flex-grow: 1;
flex-basis: 0; /* new */
}
或者,更有效地:
.sub-container > div {
flex: 1; /* fg:1, fs:1, fb:0 */
}
.container {
display: flex;
min-height: 300px;
width: 500px;
}
.sub-container {
flex: 1;
display: flex;
flex-direction: row;
}
/* ADJUSTMENT HERE */
.sub-container > div {
flex: 1;
}
.first-container {
background-color: blue;
}
.second-container {
background-color: yellow;
}
.second-container>img {
max-height: 100%;
max-width: 100%;
object-fit: scale-down;
}
<div class="container">
<div class="sub-container">
<div class="first-container">A</div>
<div class="second-container">
<img src="https://internationalbarcodes.net/wp-content/uploads/2017/04/QR%20code%20example.jpg" />
</div>
</div>
</div>
更多信息:
为了避免问题中描述的问题,作为一般规则,使用
flex
属性而不是flex-grow
,flex-shrink
和flex-basis
分别。来自 flexbox 规范:
§ 7.2.1. 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.了解更多关于 the difference between
flex-basis: auto
andflex-basis: 0
的信息
关于html - 如何使用 flex-grow 使图像填充 flex 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53828005/