CSS3 & Modern Layouts (50 Qs)•Part 1: Basic & Foundational Concepts (Junior / Entry-Level)
What is Margin Collapsing in CSS and when does it occur?
junior LevelcssBasic
In Simple Words: Margin collapsing occurs when the vertical (top and bottom) margins of two adjacent block-level elements combine into a single margin equal to the largest of the individual margins, rather than summing together:
- If Element A has
margin-bottom: 30pxand Element B hasmargin-top: 20px, the distance between them is 30px (not 50px!).
When Collapsing Occurs:
- Adjacent Siblings: Margins between two consecutive block elements in document flow.
- Parent and First/Last Child: When there is no border, padding, or inline content separating the parent's margin from the child's margin.
- Empty Blocks: An element with no height, padding, or border will collapse its own top and bottom margins together.
When Margins Do NOT Collapse:
- Horizontal (left/right) margins never collapse.
- Elements with
display: flexordisplay: grid. - Elements with
position: absoluteorfixed. - Floating elements or elements establishing a new Block Formatting Context (BFC) via
overflow: hidden.