美文网首页Interview
css实现自适应正方形

css实现自适应正方形

作者: saxon_y | 来源:发表于2021-01-14 12:27 被阅读0次

方法一:使用 CSS3vwvh 单位

  • vw% 单位设置宽度,用 vw 单位设置相同高度即可;
  • vh 单位设置宽度和高度
.square-a{
    /* width: 20%; */
    width: 20vw;
    height: 20vw;
}

方法二:使用垂直方向上的 padding 撑开容器

  • 使用 padding-bottom 撑开容器,如果容器有内容需要设置 height: 0px ,否则正方形高度会被撑开
  • 使用 padding-top 撑开容器,和前者基本相同,唯一的区别是如果 content 没有脱离文档流,content 内容会显示到容器外边,使用时需注意
.square-b {
    /* width: 20vw; */
    width: 20%;
    height: 0px;
    padding-bottom: 20%;
}

方法三:使用伪元素设置 margin 或者 padding 撑开容器

  • 利用 ::before::after 伪元素设置垂直方向的 margin 或者 padding ,需要注意 content 需脱离文档流,否则正方形会被撑开
.square-c {
    width: 20%;
}
.square-c::after {
    content: '';
    display: block;
    margin-top: 100%;
}

案例所有代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0px;
            margin: 0px;
        }

        .square-a {
            width: 20vw;
            height: 20vw;
            background-color: green;
            color: #fff;
            position: relative;
        }

        .square-b {
            /* width: 20vw; */
            width: 20%;
            height: 0px;
            padding-top: 20%;
            background-color: orange;
            color: #fff;
            position: relative;
        }

        .square-c {
            width: 20%;
            background-color: blue;
            color: #fff;
            position: relative;
        }
        .square-c::before {
            content: '';
            display: block;
            margin-top: 100%;
        }

        /* 正方形内容居中 */
        [class^="square"] div{
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    </style>
</head>
<body style="display: flex;">
    <div class="square-a"><div>正方形</div></div>
    <div class="square-b"><div>正方形</div></div>
    <div class="square-c"><div>正方形</div></div>
</body>
</html>

显示效果:


square.png

点赞、收藏的人已经开上兰博基尼了 (´▽`ʃ♡ƪ)

转载请注明出处!!!(https://www.jianshu.com/p/905bef8a320d)

相关文章

网友评论

    本文标题:css实现自适应正方形

    本文链接:https://www.haomeiwen.com/subject/ojzmaktx.html