CSS 自适应正方形

padding 使用百分数值时是根据其包含块的 width 值计算的。

With respect to the width of the containing block.

所以可以利用 height = 0; 并用 padding-bottom = 100%; 撑起一个正方形:

1
2
3
4
<div class="container">
<div class="spacer"></div>
<div class="content">item</div>
</div>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.container {
position: relative;
width: 20%;
}

.spacer {
width: 100%;
height: 0;
padding-bottom: 100%;
background: orange;
}

.content {
position: absolute;
top: 0;
left: 0;
}

参考资料

您还在局域网。 ——来自隔墙相望的评论