BFC特性 形成BFC

1、示例代码

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>BFC</title>
        <style type="text/css">
            * {
                padding: 0;
                margin: 0;
            }
        </style>
    </head>

    <body>
        <!--parent的高度是110px,若没有形成BFC的话,高度是100px-->
        <style type="text/css">
            .child {
                height: 100px;
                margin-top: 10px;
            }
            
            .parent {
                /*形成bfc*/
                overflow: hidden;
                border: 1px solid yellow;
            }
        </style>
        <div class="parent">
            <div class="child">
                1
            </div>
        </div>
        <!--同级的元素垂直编剧会重叠-->
        <style type="text/css">
            .s1 {
                height: 100px;
                margin-bottom: 20px;
                border: 1px solid red;
                overflow: hidden;
            }
            
            .s2 {
                height: 100px;
                margin-top: 30px;
                overflow: hidden;
                border: 1px solid blue;
            }
        </style>
        <div class="s1">
        </div>
        <div class="s2">
        </div>
        <!--解决方法是:将某一个同级元素已添加父元素,使父元素形成BFC-->
        <style type="text/css">
            .s1 {
                height: 100px;
                margin-bottom: 20px;
                border: 1px solid red;
                overflow: hidden;
            }
            
            .s2 {
                height: 100px;
                margin-top: 30px;
                overflow: hidden;
                border: 1px solid blue;
            }
        </style>
        <div class="s1">
        </div>
        <div style="overflow: hidden;">
            <div class="s2">
            </div>
        </div>
        <script type="text/javascript">
        </script>
    </body>

</html>

2、说明

(1)形成BFC的元素,会在垂直方向叠加margin  (说明不形成BFC的话,父子元素和同级元素都会在垂直方向重叠margin)

(2)形成BFC的元素,不会与浮动元素重叠

(3)形成BFC的元素,不会影响外面的布局;外面的布局也不会影响BFC内部布局

(4)形成BFC的元素的高度会将浮动元素计算在内。

3、形成BFC的条件

(1)float不为none

(2)position不为relative和static

(3)overflow不为visible

(4)dispaly为inline-block、table-(具有table的属性)

原文地址:https://www.cnblogs.com/mengfangui/p/10209925.html