個人前端組件 ---- 16:9固定寬高比例的div

目標:
遇到一個需求,讓圖片在頁面中,無論寬度如何變化。寬高保持16:9的比例。css

實現:html

方法一:這也是比較經典的一個方法,利用padding-bottom來實現。code

<!DOCTYPE html>
<html>
<head>
    <title>固定寬高比16:9</title>
    <style type="text/css">
        *{
            margin: 0px;
            padding: 0px;
         }
        .wrap{
            width:100%;
        }
        /* 16:9寬高比,則設padding-bottom:56.25% */
        /* height: 0px,防止矩形被裏面的內容撐出多餘的高度*/
        .box{
            width: 100vw; 
            height: 0px; 
            position: relative;
            padding-bottom: 56.25%;
            background: pink;
        }
        /* 若是須要在div裏面設置內容*/
        /* 須要設置position:absolute,才能設置內容高度100%和矩形同樣 */
        /*.box p{
            width: 100%;
            height: 100%;
            position: absolute;
        }*/
    </style>
</head>
<body>
<div class="wrap">
    <div class="box">
        <p>這是一個16:9的矩形</p>
    </div>
</div>
</body>
</html>

方法二:利用vmin來實現。htm

<!DOCTYPE html>
<html>
<head>
    <title>固定寬高比16:9</title>
    <style type="text/css">
        *{
            margin: 0px;
            padding: 0px;
         }
        .wrap{
            width:100%;
        }
        /*vmin:相對於可視窗口的寬度或高度中較小的那個,被均分爲100單位的vmin*/
        /*例:當寬度是300,高度是600,那麼50vmin則是相對於寬度的50%*/
        .box{
            height: 56.25vmin;
            background: pink;
        }

    </style>
</head>
<body>
<div class="wrap">
    <div class="box">
        <p>這是一個16:9的矩形</p>
    </div>
</div>
</body>
</html>

注意:若是屏幕寬度較大高度較小時,則能夠用vmax。若是須要隨意切換時,能夠經過js來控制。圖片

總結:
兩種方法各有利弊,方法一:兼容性好,代碼相對長點,理解也比較困難點。方法二:代碼簡潔,理清定義後便很是容易理解,可是兼容性相對差一些。不過兼容性啥的,怕什麼哈哈哈。it

相關文章
相關標籤/搜索