一、固定宽高
宽高固定是最简单的情况了,只要设置对应的宽高就可以了
height: 100px;
width: 100px;
二、利用vw
vw是相对于视口的宽度。视口被均分为100单位的vw。
height: 10vw;
width: 10vw;
三、利用padding-bottom
padding设置为百分比
时是相对于父元素
宽度计算的,利用此特性就可以实现一个固定宽高比的div
<div class="square"></div>
.square {
width: 100%;
heigth: 0;
padding-bottom: 100%;
}
四、利用伪元素 + padding-bottom + absolute
利用padding-bottom
确实可以实现正方形的效果,但是height
需要设置成0,内部就无法很好的显示子元素。
这时候我们可以利用:after
来撑高元素,再利用absolute
实现一个正方形。
<div class="square">
<div class="content">正方形</div>
</div>
.square {
width: 50%;
position: relative;
}
.square:after {
content: "";
display: block;
padding-bottom: 100%;
}
.content {
position: absolute;
width: 100%;
height: 100%;
}