banner
zmzm

zmzm

Height collapse problem of absolute positioning parent element in CSS

1 What is height collapse?#

When it comes to the height collapse of a parent element, we easily think of float. In the normal flow of a document, the height of a parent element is automatically determined by 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 floated element cannot contribute to the height of its parent element, causing the height of the parent element 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>

The height of the parent element is determined by its child element, as shown in the following image.
image

After applying float
We can see that the height of the parent element becomes 0.
image

2 Solutions to common height collapse problems#

2.1 Adding a fixed height to the parent element#

Disadvantage: Cannot adapt to the height of the child element.

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 use float directly to solve the height collapse problem. However, the height collapse caused by float is different from the one caused by absolute positioning. Only the first solution among the three common solutions mentioned above is effective.

These are just some insights from a beginner in front-end development, and there may be some shortcomings. If there are any issues with the article, please feel free to point them out!!!

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.