完善Clearfix

Author Avatar
Ninefire 6月 06, 2018
  • 在其它设备中阅读本文章

子元素和父元素的垂直外边距会发生重叠,子元素的外边距会传递给父元素。

使用空的table元素可以隔离父子元素的外边距,使其不再相邻,从而阻止垂直外边距的重叠。

例如:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>clearfix</title>
    <style type="text/css">
        .box1 {
            width: 200px;
            height: 200px;
            background: #bfa;
        }

        .box2 {
            width: 100px;
            height: 100px;
            /* 给box2设置上外边距100px */
            margin-top: 100px;
            background: orange;
        }

        /*
        解决垂直外边距重叠问题
        .box1::before {
            content: "";
            display: table;
        }
        */

        .box3 {
            width: 100%;
            border: 10px solid red;
        }

        .box4 {
            width: 100px;
            height: 100px;
            /* 设置box4浮动 */
            float: left;
            background: yellowgreen;
        }

        /*
        解决父元素高度塌陷问题
        .box3::after{
            content: "";
            display: block;
            clear: both;
        }
        */

        /* 将两个问题合并解决 */
        .clearfix::before,
        .clearfix::after {
            content: "";
            display: table;
            clear: both;
        }

        /* 兼容IE6 */
        .clearfix{
            zoom: 1;
        }
    </style>
</head>

<body>
    <div class="box3 clearfix">
        <div class="box4"></div>
    </div>
    <div class="box1 clearfix">
        <div class="box2"></div>
    </div>
</body>

</html>

戳我查看效果!

经过修改完善的clearfix是一个多功能的样式,既可以解决高度塌陷问题,又可以解决垂直外边距重叠问题。

display: table;可以将一个元素设置为表格显示。

如发现错误请联系我,谢谢你。
本文链接:http://ninefire.tk/HTML&CSS.basics/64.html