Pradeep Pandey
Pradeep Pandey

@Div_pradeep

11 Tweets 2 reads Dec 13, 2022
CSS: Margin collapse ( All you need to know ) πŸ§΅πŸ‘‡πŸ»
What is Margin Collapse in CSS?
β†’ A collapsed margin occurs when two or more block HTML elements with vertical margins (margin-top, margin-bottom) touch each other.
β†’ If one of the two margins is greater than the other, then that margin overrides the other, leaving only one margin.
β†’ This margin is called the collapsed margin.
β†’ Margin collapse occurs in several scenarios:
1. Adjacent siblings
2. A parent container and its first child element.
3. A parent container and its last child element.
4. Empty Blocks
1. Adjacent Siblings
β†’ If the two adjacent margins are positive, the resulting margin is the larger of the two.
2. Parent-first child
β†’The first descendant element collapses its top margin with the top margin of the parent element.
β†’ The resulting margin-top will be the one with the highest value.
3. Parent-last child
β†’ The bottom margins of the container and its last element also collapse into one.
4. Empty Blocks
β†’ The vertical margins of an empty block (without height or padding or content) also collapse into each other.
β†’ Ways to get rid of margin collapse:
1. Add an overflow:hidden
2. Add a padding/border.
3. Add inline content (text).
β†’ Margin collapse does not occur if the border or the padding of the container is greater than zero, even 1px of padding will interfere with the collapse.
That's a wrap!
If You liked this thread.
1. Follow @Div_pradeep for more such content around web development, resources, tips, and cheatsheet.
2. RT the first tweet to share it with other people.
I appreciate it!
Thanks for reading.

Loading suggestions...