css height 100% 无效解决方法

江河/ 2023年04月02日/ CSS教程/ 浏览 1980

想让子元素撑满父元素,首先想到的就是 height:100% ,但是却经常无效……


究其原因,大概是因为其父元素没有“固定”的高度--无法在子元素全部绘出之前计算出其高度,那么子元素的100%高度也就没有意义了。


典型的情形一,设置div的高度撑满浏览器窗口


<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>css height 100</title>
    <style>
        html, body {
            margin: 0;
            padding: 0;
            height: 100%;
        }
        .div-1 {
            width: 200px;
            height: 100%;
            background-color: red;
        }
    </style>
</head>

<body>
    <div class="div-1"></div>
</body>

</html>


典型的情形二、设置子元素的完全覆盖父元素


<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>css height 100</title>
    <style>
        .div-1 {
            position: relative;
            width: 200px;
            height: 200px;
            background-color: gold;
        }

        .div-2 {
            position: absolute;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: red;
        }

        /* 下面这种写法也可以, 这里主要是说height=100%,所以用了上面的写法 */
        /* .div-2 {
            position: absolute;
            top: 0px;
            bottom: 0px;
            left: 0px;
            right: 0px;
            background-color: red;
        } */
    </style>
</head>

<body>
    <div class="div-1">
        www.zhuige.com
        <div class="div-2"></div>
    </div>
</body>

</html>


发表评论

暂无评论,抢个沙发...

客服 工单