Margin
[[box-model]]¶
[[Which units to use#Border/margin/padding]]¶
Margin vs padding¶
One liner: margin vs padding¶
Margin - space from the box & everything else - space between siblings
Padding - space between parent and child
Only margin¶
- negative margins
- has collapsing margins
- margin-left/right has the
auto
property
When to use margin¶
Margin is like putting glue on something before you’ve decided what to stick it to, or if it should be stuck to anything.
For spacing between siblings, use layout components like Stack
function BlogPost() {
return (
<Stack>
<p>Hello world!</p>
<VideoClip />
<p>Yadda yadda yadda</p>
<SomeEmbeddedThing />
</Stack>
)
}
- Only use padding for standalone components
- you don't know where the component will be
- only margin-bottom
- no
margin-top
(predictable)
- no
- flex/grid for everything
- no collapsing margin
- a div component just for space
Negative margin¶
the only one of the three that can be negative
- will still move around the children
- because of the flow algo
- unlike
transform: translate()
margin: auto
¶
margin: auto
in flow layout¶
- left/right
margin: auto
only works if there's an explicit width - put the leftover space in the left/right
[[Positioned Layout#margin: auto
]]¶
Stretch out an image with margin¶
Get child to break free from the parent padding
When width: auto, left and right margin extend the width of the box
.stretched works if you put a paragraph in it too
- you could use
calc()
if this feels hacky, see [[CSS Grid]] and full bleed layout
<div class="card">
<p>The otter is the best</p>
+ <div class="stretched">
<img src="/otter.jpg" />
+ </div>
<p>The best</p>
</div>
.stretched {
margin-left: -32px;
margin-right: -32px;
}
.stretched img {
width: 100%; /* parent's width is made wider by the -ve margin */
}
Margin collapse¶
only in flow layout
Margin will collapse when margins are
- Vertical
- parent and child margins can merge if they're in the same direction
- horizontal doesn't collapse
- touching (adjacent)
- not blocked by
- padding/border
- another element
- a gap (child margin doesn't extend outside of parent)
- scroll container
- overflow: auto, hidden, ...
- not blocked by
This won't collapse margin
Margin increases distance between siblings - child can transfer margin to parent!
Padding gap between child and the parent's bounding box
<div style="min-height: 500px">
<p style="margin-bottom: 20px">P One</p>
<div>
<p style="margin-top: 20px">P Two</p>
![[image-20221024103552947.png]]
- including parent margin and child margin
- (both can be margin-top)
- only flow layout
- flex and grid don't have this issue
How margin gets calculated¶
- Find the largest positive margin
- Find the largest (absolute) negative margin
- add them together