HTML & CSS Interview Question #67
What is margin collapsing?
CSS Fundamentals, Selectors, Cascade, Specificity, Box Model, Units & Typography Mid-Level Intermediate
Quick Interview Answer
Vertical margins of certain block elements in normal flow can combine, or collapse, instead of being added together. This commonly occurs between adjacent block elements and between a parent and its first or last child under specific conditions.
Detailed Explanation
Vertical margins of certain block elements in normal flow can combine, or collapse, instead of being added together. This commonly occurs between adjacent block elements and between a parent and its first or last child under specific conditions.
Margin collapsing does not occur in every layout context; for example, flex and grid item margins do not collapse in the same way. Understanding the behavior helps explain unexpected vertical spacing.
Code Example
.first {
margin-bottom: 30px;
}
.second {
margin-top: 20px;
}
/* In normal block flow, the adjoining vertical
margins may collapse rather than total 50px. */