跳到主要内容

自适应正方形

/* // 这种方案和屏幕宽度强行绑定,不好 */
.container {
width: 50%;
background: #ccc;
height: 50vw;
}

/* <!-- 第二种方案,利用padding-top;注意父元素开绝对定位 --> */
.container {
width: 50%;
/* 该元素真实高度为0,我们看到的只是它往下偏移而露出的padding背景色 */
/* padding-top后的百分比以父容器**宽度**为准 */
padding-top: 50%;
height: 0;
top: 50%;
left: 50%;
position: absolute;
transform: translate(-50%, -50%);
background-color: antiquewhite;
}