保持纵横比 Mixin

Avatar of Chris Coyier
Chris Coyier

这篇文章 来自 2013 年 7 月,介绍了一种使用伪元素来保持元素纵横比的方法,即使它在缩放时也是如此。

这是一个简化了数学运算的 Sass Mixin。

@mixin aspect-ratio($width, $height) {
  position: relative;
  &:before {
    display: block;
    content: "";
    width: 100%;
    padding-top: ($height / $width) * 100%;
  }
  > .content {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }
}

Mixin 假设你将使用类名为 content 的元素嵌套在你最初的块中。像这样

<div class="sixteen-nine">
  <div class="content">
    insert content here
    this will maintain a 16:9 aspect ratio
  </div>
</div>

使用 Mixin 很简单,就像

.sixteen-nine {
  @include aspect-ratio(16, 9);
}

结果

.sixteen-nine {
  position: relative;
}
.sixteen-nine:before {
  display: block;
  content: "";
  width: 100%;
  padding-top: 56.25%;
}
.sixteen-nine > .content {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

演示

这是一个演示,展示了上述代码的实际操作。添加动画是为了展示元素在调整大小时的纵横比保持不变。

查看 Pen 保持纵横比演示 作者:Sean Dempsey (@seanseansean) on CodePen.

感谢 Sean Dempsey (@thatseandempsey) 为此做出贡献!