css 父元素高度崩塌解决办法

当父元素没有设置高度,(我们本希望它由子元素撑起来),而子元素设置了浮动,这时候子元素脱离了标准的文档流,于是父元素的高度就崩塌了,高度变为 0

<!DOCTYPE html>
<html>
<head>
    <title>ThankIT</title>
</head>
<body>
<style type="text/css">
    .parent {
        border:10px solid #f9f2f4;
    }
    .child {
        width: 100px;
        height: 100px;
        float: left;
        background-color: yellow;
        padding: 15px;
    }
</style>
<div class="parent">
    <div class="child">
        I am child
    </div>
</div>
</body>
</html>

解决方法一

设置父元素

.solution-one .parent {
        overflow: auto;
        zoom: 1;
    }
<div class="solution-one">
    <div class="parent">
        <div class="child">
            I am child
        </div>
    </div>
</div>

解决方法二

利用 after 伪元素

.solution-two .parent:after {
        content: " ";
        display: table;
        clear: both;
    }
<div class="solution-two">
    <div class="parent">
        <div class="child">
            I am child
        </div>
    </div>
</div>

完整的参考代码:

<!DOCTYPE html>
<html>
<head>
    <title>ThankIT</title>
</head>
<body>
<style type="text/css">
    .parent {
        border:10px solid #f9f2f4;
    }
    .child {
        width: 100px;
        height: 100px;
        float: left;
        background-color: yellow;
        padding: 15px;
    }
    .solution-one .parent {
        overflow: auto;
        zoom: 1;
    }
    .solution-two .parent:after {
        content: " ";
        display: table;
        clear: both;
    }
</style>
<div class="parent">
    <div class="child">
        I am child
    </div>
</div>
<div style="clear: both;height: 20px;"></div>
<div class="solution-one">
    <div class="parent">
        <div class="child">
            I am child
        </div>
    </div>
</div>
<div style="clear: both;height: 20px;"></div>
<div class="solution-two">
    <div class="parent">
        <div class="child">
            I am child
        </div>
    </div>
</div>
</body>
</html>

2 comments

  1. 笑八达

    世间博客不少,风景这边独好!

    1. Pisces Post author

      感谢留言!

发表评论

电子邮件地址不会被公开。 必填项已用*标注