Thuta Learning
CSS
IntermediateWeb DevelopmentBeginner

Margin

CSSLesson 1325 min

What you'll walk away with

  • Explain why margin: 0 auto centers a block that has a width
  • Predict the space left when two sibling margins collapse
  • Diagnose and fix a child's margin escaping through its parent
  • Write reusable spacing with margin-block / margin-inline and the stack pattern

Explain it simply

Explain it simply

Margin is the space outside a box. It lies beyond the border and keeps boxes apart from one another. It is like the distance people leave between each other in a queue: that space belongs to nobody's body. So margin is always transparent, never shows the element's background, and cannot be clicked.

Margin creates the space between sections, between a heading and its paragraph, and centers the page content. But it has one unusual behaviour: vertical margins sometimes merge (collapse) into one instead of adding up.

Problem → Why → Solution

The problem: the whole card moves instead of gaining space inside

A developer wants the heading inside a grey card to sit away from the card's top edge, so they give the h2 margin-top: 20px. They expect 20px of grey space above the heading inside the card. What actually happens is that the heading still touches the card's top edge, and the whole card moves 20px down. Raising the margin to 40px only pushes the card further away.

.card {
  background: #f1f5f9;   /* no padding, no border */
}

.card h2 {
  margin-top: 20px;      /* escapes through the card's top edge */
}

Why does this happen?

This is parent-child margin collapsing. When a block parent has no padding or border on its top side, its first child's margin-top touches the parent's own margin-top and the two merge. The merged margin appears outside the parent, so the whole card moves. If you want space inside the card, use the card's padding, not the heading's margin.

Core concept: margin, auto and collapsing

Margin uses the same shorthand as padding (one to four values, clockwise from the top), and its logical versions are margin-block and margin-inline. Unlike padding, margin can be negative: margin-top: -8px pulls an element upward and can make it overlap its neighbour. Percentage margins, like padding, are calculated from the containing block's width.

The value auto takes up the remaining space. Give a block element that has a width margin-inline: auto (or margin: 0 auto), and the browser splits the parent's leftover horizontal space equally between left and right, centering the element. Without a width, the block already fills its parent and there is nothing left to split. In normal block flow, margin-top: auto and margin-bottom: auto compute to 0, so they cannot center vertically; that only works inside flex and grid.

Margin collapsing only affects vertical (block-direction) margins, in three situations. (1) Adjacent siblings: if the upper one has margin-bottom: 24px and the lower one margin-top: 16px, the space between them is not 40px but the larger value, 24px. (2) A parent and its first or last child: when the parent has no padding or border on that side, the child's margin escapes outside the parent. (3) An empty block: its own top and bottom margins merge.

To stop collapsing, give the parent padding or a border, set display: flow-root on it, or make it a flex or grid container; margins of flex and grid items never collapse. Horizontal margins never collapse in any situation.

SituationResulting space
Siblings: bottom 24px + top 16px24px (the larger one)
Same siblings in a flex column40px (no collapsing)
Horizontal 24px + 16px40px (never collapses)
Mental model: when vertical margins touch
  1. Do two vertical margins touch?
  2. Any padding, border or content between?
  3. If not, only the larger one remains
  4. Flex or grid items: they simply add

Padding and border act as a wall between two margins; with a wall in between, nothing collapses.

General pattern

css
selector {
  margin: top right bottom left;   /* same 1-4 value rules as padding */
  margin-block: start end;         /* vertical in English and Myanmar */
  margin-inline: auto;             /* centers a block that has a width */
}

.stack > * + * {
  margin-block-start: gap;         /* space between children, set by the parent */
}

The shorthand and logical properties work just like padding. margin-inline: auto centers a block with a width, and .stack > * + * adds space above every child except the first.

Example: a centered container and heading spacing

This example is the basic layout of almost every page: content capped at 960px, centered, with breathing room on both sides on narrow screens. min() picks the smallest of the values it is given.

.container {
  width: min(100% - 32px, 960px);
  margin: 0 auto;
}

.section-title {
  margin-bottom: 16px;
}

Code breakdown

  1. Line 2width: min(100% - 32px, 960px);

    When the parent is wider than 992px this picks 960px; when narrower, the parent's width minus 32px. A 400px parent gives 368px.

  2. Line 3margin: 0 auto;

    0 top and bottom, auto left and right. Because there is a width, the leftover 32px is split into 16px per side and the container is centered. margin-inline: auto gives the same result.

  3. Line 7margin-bottom: 16px;

    Puts 16px below the heading. If the following <p> has its default 16px (1em) margin-top, the two collapse, so the gap is 16px, not 32px.

You should see
From a 992px-wide parent up, .container is 960px wide and centered. On narrower parents it is the parent's width minus 32px, leaving 16px free on each side (368px inside a 400px parent). Every .section-title has 16px of space below it.

Who owns the spacing: the stack pattern

When a component such as a card gives itself margin-top: 32px, that 32px follows it into every new context, a sidebar, a modal, the top of a page, and causes trouble where it is not wanted. A better approach is for components to own no outside margin and for the parent layout to decide the space between its children. The .stack class below does exactly that.

.stack > * {
  margin-block: 0;               /* children bring no margins of their own */
}
.stack > * + * {
  margin-block-start: 24px;      /* every child except the first */
}

/* In a flex or grid container, gap does the same job without margins */
.list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

The * + * selector means "an element that directly follows another element", so it matches every child except the first. When you reach flexbox and grid in later lessons, the gap property does the same job with no margins at all.

In real projects

Where this shows up in real projects

Nearly every website has a container class such as width: min(100% - 2rem, 70rem); margin-inline: auto;, and Tailwind's mx-auto is simply margin-inline: auto. Blogs and documentation sites control the space between headings, paragraphs, images and code blocks in an article with one parent rule like .stack, and Tailwind's space-y-6 utility is built on the same * + * idea.

Component libraries for React or Vue now ship buttons and cards with no outside margin as a standard, so the surrounding layout decides spacing wherever they are placed. Collapsing bugs of the "where does this gap above the section come from?" kind are tracked down in DevTools by selecting the child element and checking whether its orange margin highlight sticks out of the parent.

Common mistakes

Common mistakes

1. Adding sibling margins together

With p { margin-bottom: 24px; } and h2 { margin-top: 32px; }, the gap is 32px, not 56px. If the design needs 56px, put margin on one side only, for example by using margin-block-start everywhere.

2. Trying to center vertically with margin: auto in block flow

.box { width: 300px; height: 50px; margin: auto; } only centers horizontally, because vertical auto margins compute to 0 in normal block flow. To center vertically, make the parent a flex or grid container.

3. Baking outside margin into a component

Write .alert { margin: 40px 0; } and the 40px comes along to the bottom of a form, into a modal and everywhere else, forcing override after override. Keep the component margin-free and let the parent's stack or gap provide the spacing.

Best practices

Best practices

  • Adopt a rule of applying vertical spacing from one side only (margin-block-start or margin-block-end), so collapsing rarely needs thinking about.
  • Keep width: min(100% - 32px, max) and margin-inline: auto together in one reusable container class.
  • Inside flex and grid layouts, space children with gap rather than margins.

Mini challenge

Mini challenge: a monsoon reading list

Center a reading-list page and put exactly 24px between all its children. No gap may differ because of margin collapsing, and nothing inside the card may leak margin outside it.

  • Remove body's default margin and center .page with min(100% - 32px, 720px)
  • Reset the own vertical margins of .stack's direct children to 0
  • Give every child except the first margin-block-start: 24px
  • Give .card 20px of padding to keep its children's margins inside, and drop the h2's top margin
reading-list.html
<!doctype html>
<html lang="en">
<style>
  /* TODO: remove the browser's default body margin */

  /* TODO: .page - capped width with 16px free on each side, centered */

  /* TODO: .stack - children lose their own vertical margins,
     then every child after the first gets 24px above it */

  /* TODO: .card - padding (stops inner margins escaping), background, radius;
     then remove the top margin of the card's h2 */
</style>
<main class="page stack">
  <h1>Monsoon reading list</h1>
  <p>Five short books for rainy afternoons.</p>
  <section class="card">
    <h2>Fiction</h2>
    <p>Two novels and a story collection.</p>
  </section>
</main>
</html>

Expected: The page is 720px wide and centered on a 1200px screen, and 328px wide with 16px on each side on a 360px phone. Every gap between the heading, the paragraph and the card is exactly 24px, with no stray space at the top of the page. The card's heading sits 20px (its padding) below the card's top edge, inside the grey card.

Show hint

You need two rules: .stack > * zeroes the margins and .stack > * + * adds 24px back. Since * adds no specificity, both rules tie and the * + * rule wins because it comes later.

Show solution
reading-list.html
<!doctype html>
<html lang="en">
<style>
  body {
    margin: 0;
    font-family: system-ui, sans-serif;
    line-height: 1.6;
  }
  .page {
    width: min(100% - 32px, 720px);
    margin-inline: auto;
  }
  .stack > * {
    margin-block: 0;
  }
  .stack > * + * {
    margin-block-start: 24px;
  }
  .card {
    padding: 20px;
    background: #f1f5f9;
    border-radius: 12px;
  }
  .card h2 {
    margin-block-start: 0;
  }
</style>
<main class="page stack">
  <h1>Monsoon reading list</h1>
  <p>Five short books for rainy afternoons.</p>
  <section class="card">
    <h2>Fiction</h2>
    <p>Two novels and a story collection.</p>
  </section>
</main>
</html>

Quick quiz 1 / 3

Two adjacent blocks: the upper has margin-bottom: 24px, the lower margin-top: 16px. How much space is between them?

Quick quiz 2 / 3

The first h2 in a .card with no padding or border gets margin-top: 20px, and the whole card moves down. Which fix creates the space inside the card?

Quick quiz 3 / 3

In normal block flow, where does .box { width: 300px; height: 50px; margin: auto; } end up?

What to remember

  • Margin is transparent space outside the border, and unlike padding it can be negative.
  • Center a block that has a width with margin-inline: auto; vertical auto margins are 0 in block flow.
  • When vertical margins touch, only the larger remains; padding, border, flow-root or flex/grid stop it.
  • Keep components free of outside margin and let the parent's stack or gap control spacing.

CSS reference — MDN Web Docs

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Margin | Thuta Learning