通过 CSS3 的 aspect-ratio 属性实现指定宽高比的区域

844 阅读1分钟

使用场景:需要实现相关比例的视频播放区域,如16:9、4:3等,或者页面中某些按一定比例展示的图片等。

兼容性

具体写法:

  1. 可在全局样式文件或者相关的页面样式文件中添加如下初始化代码:
/* 宽高比的默认属性 */
[aspectratio] {
  position: relative;
}

[aspectratio]::before {
  content: '';
  display: block;
  width: 1px;
  height: 0;
}

[aspectratio-content] {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
}
  1. html结构如下:
<div aspectratio class="cover">
  <img aspectratio-content src="..." alt="">
</div>
  1. 相应的css样式
.cover {
  width: 200px;
  background-color: #f0f3ef;
  &::before {
    padding-top: 56.25%; /* 9/16*100% = 56.25% */
  }
  img {
    object-fit: cover; // 可根据实际业务需要修改相应属性
  }
}
  1. 最终将会生成一个16:9的封面区域。