我的前端组件 ---- 16:9固定宽高比例的div

目标:
遇到一个需求,让图片在页面中,不管宽度如何变化。宽高保持16:9的比例。

实现:

方法一:这也是比较经典的一个方法,利用padding-bottom来实现。

<!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来实现。

<!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来控制。

总结:
两种方法各有利弊,方法一:兼容性好,代码相对长点,理解也比较困难点。方法二:代码简洁,理清定义后便非常容易理解,但是兼容性相对差一些。不过兼容性啥的,怕什么哈哈哈。

猜你喜欢

转载自www.cnblogs.com/jlfw/p/11827372.html