Margins control spacing between elements. Understanding margin behavior prevents unexpected vertical gaps.
1. Margin Collapse
When two vertical margins meet, they do not add together. Instead, the browser collapses them into the single largest margin:
⊞Code Example
/* If top element has margin-bottom: 30px and bottom has margin-top: 20px,
the resulting gap is 30px (not 50px). */
.top-box {
margin-bottom: 30px;
}
.bottom-box {
margin-top: 20px;
}
2. Centering Block Elements with margin: auto
⊞Code Example
.container {
max-width: 1200px;
margin-left: auto;
margin-right: auto;
/* Shorthand: margin: 0 auto; */
}
