css实现正方形div的3种方式


效果图:

方法一:

使用vw单位

viewport

方法二:padding-bottom

 
.demo2{ width: 100%; padding-bottom: 100%;/* padding百分比相对父元素宽度计算 */ height: 0;//避免被内容撑开多余的高度 }

方法三:padding-bottom+:after+absolute

.demo3{ width: 30%; background: #ccc; position: relative; } .demo3:before { content: ""; display: block; padding-bottom: 100%; } .demo3:after{ content: "viewport"; position: absolute; top: 50%; left: 0; width: 100%; height: 50%; text-align: center; display: block; }

相关