子元素设置height:100%无效,已解决

发布时间 2023-09-08 16:08:50作者: 凿壁偷光,集思广益

想让子元素撑满父元素,首先想到的就是 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;
        }
    </style>
</head>

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

</html>