宽高自适应正方形实现

使用 CSS 实现宽度自适应、高度始终等于宽度的正方形元素

问题

如何实现一个宽高自适应的正方形?要求宽度根据父容器自适应,高度始终等于宽度。

解答

方法一:使用 vw 单位

利用视口宽度单位,让宽度和高度都基于视口宽度计算:

.square {
  width: 10%;
  height: 10vw;
  background: tomato;
}

方法二:使用 padding 撑开高度

利用 padding 百分比相对于父元素宽度计算的特性:

.square {
  width: 20%;
  height: 0;
  padding-top: 20%;
  background: orange;
}

内容需要放在绝对定位的子元素中:

<div class="square">
  <div class="content">内容</div>
</div>
.square {
  width: 20%;
  height: 0;
  padding-top: 20%;
  background: orange;
  position: relative;
}

.content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

方法三:使用伪元素 margin 撑开高度

利用子元素 margin-top 百分比相对于父元素宽度的特性:

.square {
  width: 30%;
  background: skyblue;
  overflow: hidden;
}

.square::after {
  content: '';
  display: block;
  margin-top: 100%;
}

关键点

  • vw 方法最简单,但宽度基于视口而非父容器
  • padding/margin 百分比是相对父元素的 width 计算,而非 height
  • padding 方法需要配合绝对定位放置内容
  • 伪元素方法保留了容器的正常文档流