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 the child element is set to float, 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.
The operating environment of this tutorial: Windows 7 system, CSS3 version, Dell G3 computer.
If the parent element only contains floating elements, and the parent element does not set a height and width, then its height will collapse to zero, which is the so-called "height collapse".
If the parent element contains a background or border, the overflowing element does not look like part of the parent element.
Method to solve the "height collapse" problem:
Option 1: Give the parent element a fixed height
Disadvantages: Fixing the height of the parent element violates the principle of height adaptation, is not flexible enough, and is not recommended.
Option 2: Add the attribute overflow: hidden to the parent element;
Advantages: good browser support, simple;
Disadvantage: as a child element When there is a positioning attribute, set overflow: hidden; the parts outside the container will be cropped.
[Recommended tutorial: CSS video tutorial]
Option 3: Add an empty p at the end of the child element and set the style below
div{ clear: both; height: 0; overflow: hidden; }
Advantages: All browsers support it, and container overflow will not be clipped;
Disadvantages: Adding meaningless divs to the page can easily cause code redundancy.
Option 4: Universal Clear Float Method
Add a pseudo element at the end of the content in the parent element to realize the function of the third option. The specific setting style is as follows:
Parent element:
after{ content: ""; height: 0; clear: both; display: block; }
Advantages: It will not cause code redundancy, and the remaining code performance is optimized. It is recommended to use.
For more programming related knowledge, please visit: Programming Video! !
The above is the detailed content of what is css height collapse. For more information, please follow other related articles on the PHP Chinese website!