What is height collapse and the basic method to solve it

1. What is high collapse

        In a floating layout, the height of the parent element is expanded by the child element by default

        When the child element floats, the child element will be completely out of the document flow, and the child element will be out of the document flow, and will not be able to support the height of the parent element, resulting in the loss of the height of the parent element

        After the height of the parent element is lost, the elements below it will automatically move up, causing the layout of the page to be confused. Therefore, height collapse is a common problem in floating layouts, and we must solve it.

Two, the solution

        After understanding the height collapse, we need to understand something related to it, BFC

BFC (Block Formation Context) block-level formatting environment

BFC is a hidden property in CSS that can start BFC for an element

Turn on BFC and the element will become an independent layout area

2.1 Enable BFC

        Features of elements after BFC is enabled:

                1. Elements with BFC turned on will not be covered by floating elements

                2. The outer margins of the child element and the parent element of the element with BFC enabled will not overlap

                3. Elements with BFC enabled can contain floating child elements

        The BFC of an element can be enabled in some special ways:

                1. Set the float of the element (not recommended)

                2. Set as an inline block element (not recommended)

                3. Set the element's overflow to a non-visible value

                        The common way is to set the element: overflow: hidden to enable BFC

2.2 Use after pseudo-element to solve height collapse (perfect solution)

<style>
    .box{
        border:18px red solid;
    }
    .box2{
        width:100px;
        height:100px;
        float:left;
    }
    .box::after{
        display:block;
        clear:both;
    }
</style>

2.3 Set clearfix

        The clearfix style can solve the problem of height collapse and margin overlap at the same time. When we encounter these problems, we can directly use the clearfix class

.clearfix::before,.clearfix::after{
     content:'';
     display:table;
     clear:both;
}

Guess you like

Origin blog.csdn.net/Jocks5/article/details/124407746