CSS中的宽高比

在我们等待aspect-ratio属性被更多的浏览器支持的同时,这里有一个CSS技巧(也被称为 "padding hack")来设置一个元素的长宽比。

它的工作原理是:将父元素的高度设为0,底部的内边距等于 (高度÷宽度) ×所需比率的100%。子元素应该处于绝对位置(absolute position)并继承父元素的大小。最后,我们添加object-fit:cover来防止图像失真。使用自定义属性使比率易于自定义。

HTML:

<div class="custom-aspect-ratio">
  <img src="assets/img/img.jpg" alt="Image description">
</div>

CSS:.
custom-aspect-ratio {
  --aspect-ratio: 16/9;
  position: relative;
  height: 0;
  padding-bottom: calc(100%/(var(--aspect-ratio)));
}

.custom-aspect-ratio > * {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}