我有以下 html:
<div class="main-container">
<h1>A title</h1>
<p>Some text</p>
<div class="sub-container">
<img src="">
</div>
</div>
使用以下 CSS:
.main-container{
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
.sub-container{
flex-grow:2;
background-color: green;
}
请注意,我不知道“main-container”上方容器的大小。我正在使用 flex,因为我希望“主容器”中的 div 占据底部的所有剩余空间。
我想要的是在“子容器”中有一个图像,它在两个方向(高度和宽度)都适合其父级的大小。现在,如果我将图像添加到“子容器”中,它会溢出并且根本不会缩放。 我知道 flex 仅适用于直接子级(即“子容器”而不是内部图像)。我也尝试在“子容器”上使用 flex,但我无法取得令人满意的结果。
最佳答案
这是您想要的布局吗?
使用flex: 1 1 0
来控制子容器,使用width: 100%
可以使图像适合容器。
.main-container{
border: 3px solid green;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
.sub-container{
flex-grow: 1 1 0;
background-color: green;
display: flex;
}
.sub-container img {
width: 100%;
height: 100%;
}
<div class="main-container">
<h1>A title</h1>
<p>Some text</p>
<div class="sub-container">
<img src="https://picsum.photos/1080/600">
</div>
</div>
关于css - flex 元素中的自动调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40279896/