设置绝对定位对于子元素继承父元素的高度的影响

笔者在写网页时,发现一个问题,当一个父元素没有设置高度,而全靠子元素1撑起高度时,此时子元素2就无法继承父元素的100%高度,代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        .box{
            width: 300px;
        }
        .box img{
            /*父盒子靠img撑起高度*/
            width: 300px;
        }
        .cover{
            width: 100%;
            /*设置子盒子继承父盒子的100%高度*/
            height: 100%;
            background: rgba(0,0,0,0.5);
            /*position: absolute;*/
            /*left: 0;*/
            /*top: 0;*/
        }
    </style>
</head>
<body>
<div class="box">
    <img src="images/0.jpg" alt="">
    <div class="cover"></div>
</div>
<script>

</script>
</body>
</html>

此时子盒子的高度为0;

效果如下:

接着笔者利用子绝父相原理,设置子盒子为绝对定位,父盒子为相对定位,结果,子盒子能继承父盒子被撑起的高度了,代码如下:

  *{
            padding: 0;
            margin: 0;
        }
        .box{
            width: 300px;
              /**相对定位**/
            position: relative;
        }
        .box img{
            /*父盒子靠img撑起高度*/
            width: 300px;
         
        }
        .cover{
            width: 100%;
            /*设置子盒子继承父盒子的100%高度*/
            height: 100%;
            background: rgba(0,0,0,0.5);
            /*设置定位为绝对定位,脱离标准流*/
            position: absolute;
            left: 0;
            top: 0;
        }

效果图如下:

总结:子盒子脱离标准流,子盒子以1个局外人的身份去继承父盒子的高度,而子盒子在同一个标准流时,无法继承父盒子被其他盒子撑起来的高度。

猜你喜欢

转载自blog.csdn.net/m0_38005587/article/details/81292339