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

效果图:

方法一:

使用vw单位

<div class="demo">viewport</div>
<style>
.demo{
         width: 20%;
         height: 20vw;
         background: #ccc;
       }
</style>

方法二:padding-bottom

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

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

<div class="demo3">

</div>
    .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;

        }

 

posted @ 2017-12-12 23:56  若栖1017  阅读(905)  评论(0编辑  收藏  举报