css實(shí)現(xiàn)自適應(yīng)正方形

方法一:使用 CSS3vw,vh 單位

  • vw% 單位設(shè)置寬度,用 vw 單位設(shè)置相同高度即可;
  • vh 單位設(shè)置寬度和高度
.square-a{
    /* width: 20%; */
    width: 20vw;
    height: 20vw;
}

方法二:使用垂直方向上的 padding 撐開(kāi)容器

  • 使用 padding-bottom 撐開(kāi)容器,如果容器有內(nèi)容需要設(shè)置 height: 0px ,否則正方形高度會(huì)被撐開(kāi)
  • 使用 padding-top 撐開(kāi)容器,和前者基本相同,唯一的區(qū)別是如果 content 沒(méi)有脫離文檔流,content 內(nèi)容會(huì)顯示到容器外邊,使用時(shí)需注意
.square-b {
    /* width: 20vw; */
    width: 20%;
    height: 0px;
    padding-bottom: 20%;
}

方法三:使用偽元素設(shè)置 margin 或者 padding 撐開(kāi)容器

  • 利用 ::before::after 偽元素設(shè)置垂直方向的 margin 或者 padding ,需要注意 content 需脫離文檔流,否則正方形會(huì)被撐開(kāi)
.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%;
        }

        /* 正方形內(nèi)容居中 */
        [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

點(diǎn)贊、收藏的人已經(jīng)開(kāi)上蘭博基尼了 (′▽`???)

轉(zhuǎn)載請(qǐng)注明出處?。。。?a href="http://www.itdecent.cn/p/905bef8a320d" target="_blank">http://www.itdecent.cn/p/905bef8a320d)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容