容器填充图像纵横比

Container padding image aspect ratio

我正在尝试做一个常见的把戏,但我显然做错了什么,因为我没有得到想要的结果。我正在尝试使用图像的宽高比用填充填充容器,因此它应该使容器与图像具有相同的高度。

我在网上看到要获得图像的比例,您必须这样做:

height / width * 100

HTML

<div class="box">
  <img src="..." width="100" height="150" />
</div>

CSS

.box {
  padding-bottom: 150%;
  position: relative;
  background: red;
  width: 100px;
}

.box img {
  position: absolute;
  max-width: 100%;
  opacity: 0.8;
  height: auto;
  width: 100%;
  left: 0;
  top: 0;
}

Here's a fiddle 展示我所做的。

有人知道我做错了什么吗?

您的盒子需要一个容器,因为 padding-bottom:150% 是父元素的 150%:

.container {
  width: 100%;
  max-width: 100px;
}

.box {
  padding-bottom: 150%;
  position: relative;
  background: red;
  width: 100%;
}

.box img {
  position: absolute;
  max-width: 100%;
  opacity: 0.8;
  height: auto;
  width: 100%;
  left: 0;
  top: 0;
}
<div class="container">
  <div class="box">
    <img src="https://placeholdit.imgix.net/~text?txtsize=20&txt=100%C3%97150&w=100&h=150" />
  </div>
</div>