Mastering margin collapsing - CSS: Cascading Style Sheets | MDNThe top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal), a behavior known as margin collapsing. Note that the margins of floating and absolutely positioned elements never collapse.https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing
The Rules of Margin Collapsehttps://www.joshwcomeau.com/css/rules-of-margin-collapse/
Definition: Elements' top and bottom margins are sometimes collapsed into a single margin that is equal to the larger of the two margins.
- Rule1: Only vertical margins collapse
- Rule2: Only adjacent elements collapse
- Rule3: The Bigger Margin Wins
- Rule4: Nesting doesn't prevent collapsing
- Because the parent's margin can absorb/transfer child's margin
- Unless .... (Rule 4.1)
There is another elements in-between the parent and child element
The parent element have a
height
set.The parent element have padding or border along the relevant edge.
And many more ... (see links above)
** Margins of floating and absolutely positioned elements never collapse.
Example:
- yomama & yopapa are two boxes stacked vertically (Rule #1) on top of one another (Rule #2)
- bottom margin for yomama is 20px
- top margin for yopapa is 10px
- When we inspect yomama, its bottom margin is clearly touching the yopapa box, indicating that the margins are collapsed
- When we inspect yopapa, its top margin is 10px, which is still 10px away from the yomama
- When the larger margin collapse with a smaller margin, the larger margin wins, in this case, the combined margin has the width of 20px. yomama wins! (Rule #3)
- Then, we add an extra nesting around yomama -- throw yomama in a <div>!
- Nothing really happens (Rule#4) beacuse instead of applying this margin between yomama and the parent <div>, the margin is directly transfered to the div, i.e. between div and yopapa.
- However, we can add some padding, or set a height for the parent div to prevent collapsing (Rule #4.1)
- Set height
-
- We set the height of the parent div to 90px to make space for the yomama margin
- Add padding (extra space between content -- i.e. children -- and border)
-
- We added 10px padding (the green bar) at the bottom to prevent the margin being transfered to the div box, instead, we add 10px to the original 20px margin to keep them apart.