CSS margins create transparent outer space outside an element's border, pushing neighboring elements away. Controlling vertical and horizontal margins separates headings from paragraphs, centers fixed-width containers on wide screens, and keeps page rhythm consistent.
You can pass one to four values to margin (clockwise from top: top right bottom left):
margin: 16px; applies to all four sides.margin: 16px 24px; sets top/bottom to 16px and left/right to 24px.margin: 8px 16px 24px 16px; sets top, right, bottom, left individually.margin-inline: auto; (or margin: 0 auto;) on a block element with a max-width centers it automatically inside its parent..page-container {
max-width: 960px;
margin: 0 auto;
padding: 0 16px;
}
.section-heading {
margin-top: 32px;
margin-bottom: 12px;
}
.card-stack > * + * {
margin-top: 16px;
}
When two vertical block elements touch—say an h2 with margin-bottom: 24px; right above a p with margin-top: 16px;—their margins do not add up to 40px. Instead, they collapse into the larger value (24px). Notice that margins never collapse inside Flexbox or Grid containers!
span or inline element with margin: 0 auto;: Auto horizontal margins only center block-level elements that have an explicit width or max-width.span: Vertical margins are ignored on display: inline elements; use inline-block or block.gap in Flex/Grid layouts: Inside Flexbox or Grid, prefer gap: 16px; instead of fragile child margins.Use margin for spacing outside an element's border between separate components, and padding for breathing room inside an element's background and border.
Yes. Negative margins like margin-top: -12px; pull an element closer or create overlapping badges, though overusing them can obscure sibling text.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.