Skip to content

Margin

[[box-model]]

Margin - space from the box & everything else - space between siblings

Padding - space between parent and child

Margin vs padding

Only margin

  • negative margins
  • has collapsing margins
  • margin-left/right has the auto property

When to use margin

Margin considered harmful

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>
  )
}

Syntax FM Margin episode

  • Only use padding for standalone components
    • you don't know where the component will be
  • only margin-bottom
    • no margin-top (predictable)
  • 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

  • left/right margin: auto only works if there's an explicit width
  • put the leftover space in the left/right
margin-left: auto;
width: 24rem;

margin-top: auto; /* spec says 0 */

Margin Collapse

[[css-flow-layout#Margin collapse]]

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-can-go-through-parent-padding.png margin-stretched-out.png


Last update: 2023-02-03