Hi! Today I will discuss different types of collapsing in CSS, and how to fix them.
What is the definition of collapsing?
Collapsed element is an element with a zero height.
Types of collapses that we will discuss:
1- Floating Elements Collapse.
2- Margin Collapse.
3- Absolute Positioning Collapse.
4- Empty Div Collapse.
Floating Elements Collapse.
This is a common problem with floated elements.
If we have an element, that contains nothing but floated elements, then this parent element will collapse.
Fixing it
We will apply the famous βclear-fixβ to fix this problem.
Itβs a fix applied to the after pseudo-element of the parent element.
Margin Collapse.
Margin collapse happens when you set margin-top for an element, and margin-bottom for the element above it, then the total margin between the two elements is the max-margin between both of them, not the sum of the two margins.
Fixing it
To eliminate that effect, set one of the two elements' display to be inline-block.
Absolute Positioning Collapse.
This type of collapsing happens if the parent container that holds the absolute elements doesn't have an explicit height or width, it will collapse.
Fixing it
The solution is to give the parent container an explicit height or width.
Note: When you gave it a height, don't use percentages, as the parent of this parent (body) is not specified explicitly.
Empty Div Collapse.
If we have an empty div, with no content, then it will collapse.
Fixing it
We could insert some content in the div, by writing the HTML special entity   that corresponds to space.
Another solution is to set a min-height, or a height (with no percentages) for the div.
That's it for today! I hope you learned from it. Good luck!
Top comments (9)
For the empty div I would add the following CSS:
This will trigger the creation of a linebox without having to add a space inside your div.
Thanks!
and in case you are sure the div is empty you can do
Without css elements of website are like sheeps without shepherd
If you donβt care about IE11 (or earlier) you can use display: flow-root which both clears floats and stops margin collapse.
Didn't know that, Thank you!
Nice list, the absolute positioning collapse is a sneaky one.
Don't all these have to do with the concept of Block Formatting Context (BFC)? It would be nice to explore that topic as a whole.
Thanks for your suggestion! I will try to write about it in the future.
just understand how to do and what it for, thank you!