Collapse of the space

  • If you set a child element to float, it will break away from the original document flow, the space it occupied will be freed, and the height of the corresponding parent element will be lost (to 0). This problem is called space collapse.

Such as:

<body>
    <div class="parent">
        <div class="child" id="child1"></div>
        <div class="child" id="child2"></div>
        <div class="child" id="child3"></div>
    </div>
    <div class="other"></div>
</body>
Copy the code

When no float is set, the situation is roughly as follows:

The child {float: left; }Copy the code

After setting the float:

  • As you can see, the height of the floating parent element is 0 (red), and the width and height of the child element are spread by the element itself. The other, which should be below, occupies the height of the parent element.

Solutions to space collapse:

  1. The parent element sets overflow hiding

It works by triggering the BFC

.father{
    overflow:hidden;
}
Copy the code
  1. Sets the height of the parent element
.father{
    height:100px;
}
Copy the code
  1. Add a child element (the last one) to the parent element and clear the float
#child4{
    width:0;
    height:0;
    clear:both;
}
Copy the code
  1. The parent element sets the ClearFix class

The principle is the same as 3, except that the elements that need to be cleared float are batched

/* Add to the parent elementclassattributeclearfix* /
.clearfix::after{
    content: ' ';
    display: block;
    clear: both;
}
Copy the code