CSS: 如何使用vw和vh实现16/9比例的div?

4

我有以下设置:

#container {
  width: 100vw;
  height: calc(100vw / 1.77);
  display: block;
  background-color: black;
}
<div id="container">
</div>

我希望始终保持16:9的纵横比。

但它没起作用!我做错了什么吗?


2
定义“它不工作”。 - str
2个回答

8

#container {
  display: block;
  width: 100vw;
  max-width: 177.78vh;
  /* 16/9 = 1.778 */
  height: 56.25vw;
  /* height:width ratio = 9/16 = .5625  */
  max-height: 100vh;
  background-color: black;
}
<div id="container">
</div>


谢谢,它有效。 - stighy

0
这是一个 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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接