如何将图像高度限制为另一个flexbox列的高度



我有一个带有两列的flexbox布局。第一列包含一个图像,在设计时该图像的纵横比未知。我想显示整个图像,同时保持其纵横比。第二列包含几行文本,设计时长度未知。容器不应具有固定的高度。

如何在图像高度不超过第二列(文本(高度的情况下,最大限度地增加第一列中图像的可用空间?

在下面的代码片段中,我希望黑色图像的高度小于或等于灰色背景的右列,它永远不应该更高。

.row {
display: flex;
padding: 5px;
margin: 5px;
align-items: flex-start;
background-color: blue;
}
.col1 {
flex-grow: 1;
background-color: yellow;
align-self: stretch;
}
.col2 {
background-color: lightgray;
padding: 10px;
min-width: 300px;
}
img {
width: 100%;
height: 100%;
max-height: 100%;
object-fit: contain;
}
<div class="container">
<div class="row">
<div class="col1">
<img src="https://dummyimage.com/256x256/000/fff">
</div>
<div class="col2">
<p>Here's some text</p>
<p>And some more text</p>
<p>And some more text</p>
</div>
</div>
</div>

您可以通过height:0;+min-height:100%获得平均结果,但父级的宽度几乎不会更新。

.row {
display: flex;
padding: 5px;
margin: 5px;
background-color: blue;
justify-content:start;
}
.col1 {
flex: 1 1 auto;
background-color: yellow;
align-self: stretch; 
}
.col2 {
background-color: lightgray;
padding: 10px;
flex:1 0 auto; 
}
img {  
height:0;
min-height: 100%; 
min-width:100%;
object-fit: contain;
}
<div class="container">
<div class="row">
<div class="col1">
<img src="https://dummyimage.com/256x256/000/fff">
</div>
<div class="col2">
<p>Here's some text</p>
<p>And some more text</p>
<p>And some more text</p> 
</div>
</div>
</div>

要获得这种结果,需要固定其中一个列的宽度。在下面的示例中,我已将图像的宽度固定为256px

.row {
display: flex;
padding: 5px;
margin: 5px;
align-items: flex-start;
background-color: blue;
}
.col1 {
flex: 0 0 256px;
background-color: yellow;
}
.col1 > img {
width: 256px;
}
.col2 {
flex: 1;
background-color: lightgray;
padding: 10px;
}
<div class="container">
<div class="row">
<div class="col1">
<img src="https://dummyimage.com/600x600/000/fff">
</div>
<div class="col2">
<p>Here's some text</p>
<p>And some more text</p>
<p>And some more text</p>
<p>And some more text</p>
<p>And some more text</p>
<p>And some more text</p>
</div>
</div>
</div>

相关内容

最新更新