CSS Margins
CSS Margins: Outer Spacing, Centering, and Margin Collapse
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.
Margin Shorthand and Auto Centering
You can pass one to four values to margin (clockwise from top: top right bottom left):
- 1 value:
margin: 16px;applies to all four sides. - 2 values:
margin: 16px 24px;sets top/bottom to16pxand left/right to24px. - 4 values:
margin: 8px 16px 24px 16px;sets top, right, bottom, left individually. - Horizontal Centering: Setting
margin-inline: auto;(ormargin: 0 auto;) on a block element with amax-widthcenters 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;
}
Understanding Vertical Margin Collapse
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!
Common Mistakes to Avoid
- Trying to center a
spanor inline element withmargin: 0 auto;: Auto horizontal margins only center block-level elements that have an explicitwidthormax-width. - Adding top and bottom margins to pure inline tags like
span: Vertical margins are ignored ondisplay: inlineelements; useinline-blockorblock. - Forgetting
gapin Flex/Grid layouts: Inside Flexbox or Grid, prefergap: 16px;instead of fragile child margins.
Frequently Asked Questions
When should I use margin instead of padding?
Use margin for spacing outside an element's border between separate components, and padding for breathing room inside an element's background and border.
Are negative margins valid in CSS?
Yes. Negative margins like margin-top: -12px; pull an element closer or create overlapping badges, though overusing them can obscure sibling text.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.