What is height collapse?

Table of contents

highly collapsed

Methods to solve high collapse


Since the height collapse and margin overlap were confused before, let’s re-write the height collapse

highly collapsed

In the document flow, the height of the parent element is expanded by the child elements by default, that is, the height of the child element is the same as the height of the parent element. However, when float is set for a child element, the child element will completely break away from the document flow. At this time, the child element will not be able to support the height of the parent element, causing the height of the parent element to collapse. Since the height of the parent element collapses, all elements under the parent element will move upward, which will lead to chaotic page layout.

Methods to solve high collapse

1. Therefore, we must avoid the problem of height collapse during development. We can write the height of the parent element to death to avoid the collapse problem. However, once the height is written to death, the height of the parent element will not automatically adapt to the height of the child element. , so this solution is not recommended.

2. You can directly add a blank div at the end of the height-collapsed parent element. Since this div does not float, it can expand the height of the parent element, and then clear the float, so that you can use this Use a blank div to expand the height of the parent element, which has basically no side effects. Although using this method can solve the problem, it will add redundant structure to the page. ​ Clear attribute value: ​ none: Default value, sort according to the sorting rules of floating elements (left floating element, find left floating element, right floating element, right floating element) left: Do not look for the previous left floating element Right: Do not look for the previous one Right floating element​ both: Don’t look for the previous left floating element and right floating element​

.clear{
    clear: both;
}

3. Through the after pseudo-class​ You can add a blank block element to the end of the element through the after pseudo-class, and then clear the float. This is the same principle as adding a div, and can achieve the same effect, and will not Adding extra divs to the page is our most recommended method and has almost no side effects.

.parent:nth-child(2)::after{
    content: "";
    display: block;
    clear: both;
}

4. Enable bfc for the parent element

 For details on BFC, see What is margin collapse and What is BFC? (12)_The blog of the dog-headed Sudan who learns front-end-CSDN blog

Guess you like

Origin blog.csdn.net/qq_53866767/article/details/132378468