如何使img高度取决于容器的高度,容器的宽度取决于img的纵横比?

  • 本文关键字:取决于 高度 img 何使 html css flexbox
  • 更新时间 :
  • 英文 :


HTML:

<div class="vertical-flexbox">
<div id="card">
<div id="image-wrapper">
<img src="assets/myImage.png" alt="picture">
</div>
</div>
</div>


.CSS:

.vertical-flexbox {
height: 100%;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
#card {
background-color: gray;
margin: 20px;
padding: 20px;
min-height: 0;
min-width: 0;
height: 80%;
display: flex;
}
#image-wrapper {
flex: 1;
overflow: hidden;
}
img {
height: 100%;
}

div#card元素的动态高度等于身体高度的 80%。

img的高度应由弹性框决定,其宽度应基于高度以保持原始纵横比

div#card宽度应取决于宽度img以使其适合。

如何实现此效果?

如果.vertical-flexbox的大小可以调整为height: 100vh;或一定数量的px则图像的object-fit: contain;应该可以根据需要工作:

.vertical-flexbox {
height: 100vh;  /* <-- here some 'hard' value */
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
#card {
background-color: gray;
margin: 20px;
padding: 20px;
min-height: 0;
min-width: 0;
height: 80%;
display: flex;
}
#image-wrapper {
flex: 1;
overflow: hidden;
height: 100%;
}
img {
height: 100%;
object-fit: contain; /* <-- to save aspect ratio */
}
<div class="vertical-flexbox">
<div id="card">
<div id="image-wrapper">
<img src="https://picsum.photos/600/1000" alt="picture">
</div>
</div>
</div>

最新更新