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

时间:2020-06-11 21:29:07

标签: 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的高度应由flexbox决定,其宽度应基于高度以保持原始长宽比

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

如何实现此效果?

1 个答案:

答案 0 :(得分:0)

如果.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>