Why does this CSS margin-top style not work?
⚡TLDR
If your margin-top
is acting the invisible man, it might be due to margin collapse
. Try adding overflow: hidden;
or use the diplomatic padding-top
instead.
Playing with an inline
display? margin-top
prefers a block
party.
Or, get rid of collapsing margins - throw display: inline-block;
or float:left;
on the child.
What are collapsing margins anyway?
The CSS box model has a trick up its sleeve - collapsing margins. Here's a cheat sheet:
- Adjacent vertical margins meet, have a debate, and the biggest margin wins! The smaller one vanishes.
- Horizontal margins don't vanish. They sit chill, side by side.
- For an element's top and bottom margins to collapse, they need a clear path - no padding, borders, or other elements in their way.
A new context for everyone!
Block formatting context is our friend in the fight against collapsing margins. It's created in a few ways:
- Do a magician's float with
float: left;
orfloat: right;
. Presto! New context! - Change
overflow
from its favorite spot ofvisible
to something else. - Let the
display
property inviteinline-block
,table-cell
, orflex
to the party.
Beware the collapsing margin scenarios
These scenarios are where margins go incognito:
- Parent and child: When these two have matching vertical margins, they collapse. You can prevent this with pseudo-elements, borders, or padding.
- Empty blocks: Margins of an empty block collapse into itself.
min-height
can help contain this. - Adjacent siblings: Their margins collapse, too. But, inline elements, or
clear: both;
can save the day here.
Pro tips for side-stepping margin collapses
Here are some sneaky ways to make margins behave:
- Floats and clears: Old siblings with annoying sibling rivalry, but handy in a pinch.
- Inline-block elements: Good for smaller layouts and vertical alignments.
- Flexbox and Grid: Modern kids on the block. They outright ignore vertical collapsing margins.
- Padding over margins: Sometimes, padding does the job without causing a collapse.
Achieving mastery over margin behavior
Tips to master complex layout behavior:
- Stacking contexts: Margins inside a local stacking context don't mix with those outside.
- Positioned elements: Absolutely positioned elements' margins are solo artists, they don't mingle.
- Table cells: Margins on table cells and their height operate on different rules.
- W3C spec: Understanding W3C lingo can save you hours of debugging.
Linked
Linked
Was this article helpful?