CSS设置元素宽高比
注册

CSS设置元素宽高比

CSSaspect-ratio属性可以明确元素的高宽比例,一定是一个高频使用的CSS属性。

例如:

.box {
    aspect-ratio: 10 / 1;
    background: deepskyblue;
}
.img-size {
    aspect-ratio: 1 / 1;
}

不过稍老的浏览器版本不支持这个属性。

传统方式

利用padding-topcss变量实现。

<div class="media media-diy" style="--bili:75;">
<img class="media-content" src="url" style="width:100%;height:100%">
</div>

其中的变量75实际是高和宽的比值是75%对应的就是,宽高比为4比3,这里使用变量实际是为了更灵活的使用,如果这是固定几种比例,可以完全写死几个固定比值的class

.media {
  position: relative;
  display: block;
  padding: 0;
  -ms-flex-negative: 0;
  flex-shrink: 0;
  overflow: hidden;
}
.media-content {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  border: 0;
  margin: 0;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: 50% 50%;
  background-color: rgba(120, 120, 120, 0.1);
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
}
.media:after {
  content: '';
  display: block;
  padding-top: 100%;
    background-repeat: no-repeat;
    background-position: 50%;
}
.media-diy:after {
  padding-top: calc(var(--bili) * 1%);
}

MASTER 更新于2026-01-06 发布于2026-01-06 79

大纲
加载中