1 What is height collapse?#
When it comes to the collapse of the parent element's height, we easily think of float. In the normal flow of the document, the height of the parent element is automatically determined by the height of its child elements, meaning that the height of the parent element is the same as the height of its child elements by default. However, when an element is set to float, it completely removes itself from the normal flow of the document. As a result, the element can no longer contribute to the height of the parent element, causing the parent element's height to collapse to 0. This is called height collapse.
Normal Code
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.inner {
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div class="outer">
<div class="inner"></div>
</div>
</body>
</html>
By default, the height of the parent element is determined by its child elements, as shown in the image below.
After applying float
We can see that the height of the parent element becomes 0.
2 Solutions to common height collapse problems#
2.1 Adding a fixed height to the parent element#
Disadvantage: Unable to adapt to the height of the child elements.
2.2 Setting overflow for the parent element#
.outer {
overflow: hidden;
}
2.3 Adding a pseudo-element to the parent element#
.outer::after {
content: '';
display: block;
clear: both;
}
3 Solutions to height collapse caused by absolute positioning of the parent element#
Usually, when we encounter height collapse problems, we think of float and directly use float to solve the height collapse problem. However, the height collapse caused by float is different from the height collapse caused by absolute positioning. Among the three common solutions mentioned above, only the first one is effective for absolute positioning.
These are just some insights from a beginner in frontend development, and there may be some shortcomings. If there are any issues with the article, please feel free to point them out!