Chapter 10 of 33

Margin & Padding

Good design is mostly about space. Look at any well-designed app: the text isn't glued to the edges of its cards, buttons have room around their labels, and sections are clearly separated. In CSS, nearly all of this spacing comes from two properties you met in The Box Model: padding (space inside the border) and margin (space outside the border).

In this chapter we look at both in detail: the shorthand syntax, percentages, centring with auto, negative margins, logical properties, and the rule that confuses almost every beginner: margin collapsing.


Padding vs Margin

Padding is the space between an element's content and its border. Margin is the space between an element's border and the surrounding elements.

          margin (outside, transparent)
       ┌───────── border ─────────┐
       │  padding (inside, shows  │
       │  the background colour)  │
       │     ┌──────────────┐     │
       │     │   content    │     │
       │     └──────────────┘     │
       └──────────────────────────┘

How do you decide which one to use? Ask: "Should this space belong to the element, or sit between elements?"

FeaturePaddingMargin
PositionInside the borderOutside the border
Shows background colour/imageYesNo, always transparent
Part of the clickable areaYes (a link or button with padding is easier to tap)No
Negative valuesNot allowedAllowed
auto valueNot allowedAllowed (used for centring)
Collapses with neighboursNeverVertical margins can collapse
Included in border-box widthYesNo

Typical usage: a button gets padding so its label has room and its coloured area grows; the gap between two cards is margin (or, inside flex and grid layouts, the gap property you will meet in Flexbox).


The Four Sides

Each property has one longhand per side:

.box {
  padding-top: 10px;
  padding-right: 20px;
  padding-bottom: 10px;
  padding-left: 20px;

  margin-top: 0;
  margin-right: auto;
  margin-bottom: 24px;
  margin-left: auto;
}

Writing four lines every time is tedious, so both properties have a shorthand.

The shorthand: 1, 2, 3 or 4 values

ValuesExampleTopRightBottomLeft
1padding: 10px;10101010
2padding: 10px 20px;10201020
3padding: 10px 20px 30px;10203020
4padding: 10px 20px 30px 40px;10203040

How to remember it:

  • 4 values go clockwise from the top: top, right, bottom, left. A popular memory trick is "TRouBLe" (T-R-B-L).

  • 2 values mean "vertical horizontal".

  • With fewer values, any missing side copies its opposite: left copies right, bottom copies top.

padding: 10px 20px 30px;

   top    = 10px            (given)
   right  = 20px            (given)
   bottom = 30px            (given)
   left   = missing → copies right = 20px

Shorthands reset every side they cover. If you write margin-top: 50px; and then margin: 0; afterwards, the top margin becomes 0. When you want to change one side only, use the longhand.


Values You Can Use

  • Lengths: px, rem, em and the other units from CSS Units.

  • Percentages: relative to the width of the containing block, for all four sides (see below).

  • auto: margins only. The browser calculates the value.

  • Negative values: margins only.

.ok  { padding: 1rem; margin: -10px auto 2em; }
.bad { padding: -10px; }   /* invalid: whole declaration ignored */
.bad { padding: auto; }    /* invalid as well */

Percentages use the width, even for top and bottom

.parent { width: 400px; }
.child {
  padding-top: 25%;   /* 25% of 400px = 100px */
  margin-top: 10%;    /* 10% of 400px = 40px */
}

Chrome computes padding-top: 100px and margin-top: 40px: both from the parent's width, not its height. Why? Block heights usually depend on their content, so using height would create circular calculations. Using the width also means percentage padding is equal on all sides for a square look.

Developers used to exploit this to make boxes with a fixed aspect ratio: padding-top: 56.25% (= 9/16) makes a 16:9 box. Today you should simply use aspect-ratio: 16 / 9, but you will still see the old "padding hack" in existing code.


Centring with margin: auto

The classic way to centre a block horizontally:

.container { width: 800px; }
.box {
  width: 500px;
  margin: 0 auto;   /* top/bottom 0, left/right auto */
}

How the browser calculates it: for a block box, the left margin, border, padding, width and right margin must add up to the container's width. If both side margins are auto, the leftover space is split equally.

leftover = 800 − 500 = 300px
margin-left = margin-right = 300 / 2 = 150px

Chrome places the box exactly 150px from the container's left edge.

Three conditions for this to work:

  1. The element is a block box (inline elements ignore auto margins).

  2. It has a width narrower than the container (with width: auto it fills the space, so there is nothing to share). max-width is often used instead: max-width: 700px; margin-inline: auto;.

  3. It is in normal flow (not floated).

Only one side auto pushes the box to the other side:

.right {
  width: 200px;
  margin-left: auto;   /* all leftover space goes on the left */
}

In a 600px container, this box starts at 400px and sits flush against the right edge.

margin: auto does not centre vertically in normal block layout: vertical auto margins are treated as 0. Vertical centring becomes easy with Flexbox and CSS Grid, where auto margins work in both directions. And to centre text inside a box, use text-align: center, not margins.


Negative Margins

A negative margin pulls the element (or its neighbours) in the opposite direction, letting boxes overlap or extend beyond their parent's padding.

.card { padding: 20px; }

.card .full-bleed-image {
  margin-left: -20px;
  margin-right: -20px;   /* image stretches across the card's padding to the border */
}
Negative margin onEffect
margin-top / margin-leftMoves the element itself up / left
margin-bottom / margin-rightPulls the following content up / left onto it
Both sides of a width: auto blockMakes the element wider than its container

Use them sparingly. They're fine for a small visual adjustment, but a layout built on many negative margins becomes very hard to understand.


Margin Collapsing

Now the famous one. Write two paragraphs:

.first  { margin-bottom: 30px; }
.second { margin-top: 20px; }

You might expect 30 + 20 = 50px between them. The real gap is 30px.

Margin collapsing: when the vertical margins of block boxes in normal flow touch each other, they combine into a single margin instead of adding up.

Why would CSS do this? Think about text documents. Browsers give paragraphs a default margin of 1em above and below. If margins added up, the gap between two paragraphs would be 2em, while the gap above the first paragraph would only be 1em. Collapsing makes the spacing even everywhere, which is what you want for text. The rule comes from the document-styling roots of CSS.

How the size of the collapsed margin is calculated

Margins that touchRuleExampleResult
All positiveThe largest wins30px and 20px30px
One positive, one negativeLargest positive + most negative (they are added)30px and −10px20px
All negativeThe most negative wins−10px and −25px−25px (the boxes overlap by 25px)

We measured all three in Chrome; the gaps between the boxes were exactly 30, 20 and −25 pixels.

Where collapsing happens

There are three situations.

1. Adjacent siblings. The bottom margin of one block and the top margin of the next, as above.

2. Parent and first/last child. If nothing separates a parent's top edge from its first child's top margin, the child's margin collapses with the parent's and appears outside the parent:

.parent { background-color: #eee; }
.child  { margin-top: 40px; }
<div class="parent">
  <div class="child">Child</div>
</div>

You probably expect a grey band of 40px above the child, inside the parent. Instead, the grey parent itself moves 40px down, and the child sits right at the parent's top edge. In Chrome, the child's top was 0px from the parent's top, and the parent had been pushed down by the 40px. This is the classic "my margin escaped from its container" bug, and the same thing happens at the bottom with the last child.

3. Empty blocks. A block with no content, padding, border or height lets its own top and bottom margins collapse into one, and they then collapse with the neighbours too. In our test, a 30px bottom margin, an empty div with 20px/30px margins, and the next block gave a total gap of just 30px.

When margins do NOT collapse

  • Horizontal margins never collapse. Only top and bottom (block-direction) margins do.

  • Between a parent and child when the parent has padding or a border on that side, or inline content or clearance separates them.

  • When the parent creates a new block formatting context (BFC): for example display: flow-root, overflow other than visible or clip, or display: inline-block. A BFC keeps its children's margins inside.

  • For flex items and grid items. Inside a flex or grid container, margins never collapse. In our test, a 30px and a 20px margin inside a column flexbox gave a 50px gap.

  • For floated and absolutely positioned elements (covered in Float & Clear and Positioning).

Fixing the escaping margin

/* Option 1: the modern, side-effect-free fix */
.parent { display: flow-root; }

/* Option 2: separate the margins with padding (or a border) */
.parent { padding-top: 1px; }

/* Option 3: use padding on the parent instead of margin on the child */
.parent { padding-top: 40px; }
.child  { margin-top: 0; }

With display: flow-root on the parent, Chrome put the child 40px below the parent's top edge, inside the grey background, exactly as originally intended. display: flow-root exists for this purpose: it creates a BFC without the side effects of tricks such as overflow: hidden, which can clip shadows and dropdowns.

Avoiding collapsing problems in the first place

Many teams follow a simple convention: use margins in one direction only, for example only margin-bottom (or only margin-top) between stacked elements. Then sibling margins never meet. A popular pattern adds space only between siblings:

.stack > * + * {
  margin-top: 1rem;   /* every child except the first gets space above it */
}

For layouts built with flexbox or grid, gap is even simpler and never collapses.


Padding and Margin on Inline Elements

As you saw in The Box Model, inline elements like <span> and <a> accept padding and margin, but:

  • Left and right padding and margin push neighbouring text away normally.

  • Top and bottom padding is painted (the background grows) but does not push the lines of text apart, so it can overlap the lines above and below.

  • Top and bottom margins have no effect.

/* A link that looks like a button: */
.btn-link {
  display: inline-block;   /* now vertical padding and margin really take space */
  padding: 0.5em 1em;
  margin: 0.25em;
  background-color: #2563eb;
  color: white;
}

Using em here is deliberate: if the button's font size grows, its padding grows with it.


Logical Properties: Margin and Padding for Every Language

left and right assume text runs left to right. In Arabic or Urdu (right to left), or in vertical Japanese text, "the side where text starts" is different. Logical properties name sides by text direction instead:

Logical propertyFor English (left-to-right, horizontal)
margin-block-startmargin-top
margin-block-endmargin-bottom
margin-inline-startmargin-left (becomes right in RTL)
margin-inline-endmargin-right
margin-blocktop and bottom together
margin-inlineleft and right together

The same names exist for padding (padding-block, padding-inline-start, etc.). They work in all modern browsers, and they make common code shorter:

.container {
  max-width: 70rem;
  margin-inline: auto;      /* centre horizontally */
  padding-inline: 1rem;     /* side padding, so text never touches the screen edge */
  padding-block: 2rem 3rem; /* top 2rem, bottom 3rem */
}

We go deeper into this in Modern CSS: :has(), Nesting, clamp() & Logical Properties.


Browser Default Margins

Many elements come with margins from the browser's built-in style sheet: <body> has 8px on all sides, paragraphs and lists have 1em top and bottom, headings have their own margins, and lists also have a left padding of 40px for the bullets. That's why a page with no CSS still isn't touching the window edge. Most projects start by resetting some of these:

body { margin: 0; }
h1, h2, h3, p, ul, ol { margin-top: 0; }   /* then add spacing deliberately */

Common Mistakes

  • Using margin when you want a coloured space. Margin is transparent; use padding to grow the background.

  • Reading 3-value shorthand wrong. margin: 10px 20px 30px means top 10, left and right 20, bottom 30.

  • Expecting margin: 0 auto to centre an element without a width, an inline element, or vertically.

  • Negative or auto padding. Both are invalid and silently ignored.

  • Expecting padding-top: 10% to use the parent's height. It uses the width.

  • Adding up vertical margins and getting the wrong gap: adjacent vertical margins collapse to the largest.

  • A child's top margin pushing the whole parent down. Give the parent display: flow-root, padding or a border.

  • Forgetting the default body margin of 8px and wondering why a full-width header has a white edge.


Interview / Exam Questions

1. What does margin: 5px 10px 15px set on each side?

Top 5px, right 10px, bottom 15px, left 10px (left copies right).

2. Two stacked divs: the first has margin-bottom: 40px, the second margin-top: 25px. What is the gap? What if the second's margin were -15px?

Both positive: the larger wins, 40px. With 40px and −15px: 40 + (−15) = 25px.

3. Do margins collapse inside a flex container?

No. Flex items' (and grid items') margins never collapse, so 40px and 25px would give a 65px gap.

4. A container is 1000px wide. A child has width: 640px; margin: 0 auto; padding: 0 20px; with default content-box. What is each side margin?

The child's border box is 640 + 2×20 = 680px. Leftover = 1000 − 680 = 320px, so each margin is 160px.

5. A parent 500px wide has a child with padding: 10%. What is the child's top padding?

Percentages for padding use the containing block's width on all sides: 10% × 500 = 50px.

6. Why does a child's margin-top sometimes appear above its parent instead of inside it? Give two fixes.

Parent-child margin collapsing: with no border, padding or content separating them, the child's top margin merges with the parent's. Fixes: display: flow-root on the parent (creates a block formatting context), adding padding-top or border-top to the parent, or making the parent a flex/grid container.

7. Can padding be negative? Can margin be auto?

Padding cannot be negative (the declaration is invalid). Margin can be auto, which is how horizontal centring of blocks works.


Summary

  • Padding is inside the border, shows the background and adds to the clickable area. Margin is outside, transparent, and separates elements.

  • Shorthands take 1 to 4 values clockwise from the top (top, right, bottom, left); missing sides copy their opposite.

  • Percentage padding and margin are based on the containing block's width on all four sides.

  • margin: 0 auto centres a block that has a width; one auto side pushes the box to the other side. Vertical auto margins are 0 in block layout.

  • Margins can be negative; padding cannot.

  • Adjacent vertical margins collapse: largest positive plus most negative. This happens between siblings, between parent and first/last child, and through empty blocks, but never horizontally, never in flex/grid, and not across padding, borders or a new BFC.

  • Logical properties like margin-inline and padding-block adapt to the writing direction.

Next, in Borders & Outlines, we will style the frame that sits between padding and margin.