ScreenshotNeo

BlogGuides

CSS Spacing: Margin, Padding, and Gap Explained

Learn where margin, padding, and gap put space, how box sizing changes dimensions, why margins collapse, and how to debug unexpected spacing.

By the ScreenshotNeo team4 October 20268 min read

Use padding for space inside an element’s border, margin for space outside an individual element’s border, and gap for gutters owned by a grid, flex, or multi-column container. These properties solve different spacing problems, and a component can use more than one: for example, a card can have padding inside while its parent uses gap between cards.

1. The CSS box model: where the space goes

Read an element’s box from the inside out:

  1. Content: text, an image, or child elements.
  2. Padding: space between the content and the border.
  3. Border: the edge around the content and padding.
  4. Margin: space outside the border, separating the element from surrounding content.

A background is painted through the padding area, so padding gives content room within a colored or bordered component. Margin stays outside the border box. See MDN’s introduction to the CSS box model and CSS box model reference.

How box-sizing changes width and height

box-sizing determines what a declared width or height measures:

  • content-box (the initial behavior): width and height describe the content area. Padding and border add to the rendered dimensions.
  • border-box: width and height include content, padding, and border.

Margin remains outside in either model. A common project-wide rule is:

*,
*::before,
*::after {
  box-sizing: border-box;
}

For example, with a declared width of 300px, horizontal padding of 20px on each side, and a 2px border on each side, content-box produces a 344px border-box width (300 + 40 + 4). With border-box, the border box is 300px wide and the content area is 256px. Any margin adds space outside that box.

2. Margin, padding, and gap compared

Property Where the space is Who owns it Common use
padding Inside the border The element Keep text or controls away from a card’s edge
margin Outside the border An individual element Separate an element from surrounding content
gap Between layout items The grid, flex, or multi-column container Set consistent gutters between siblings

Use the property that matches where the space belongs. Padding is not a substitute for margin, and neither is a substitute for a container’s gap. They can work together when the layout calls for it.

Padding: room inside a component

Choose padding when content should have breathing room from the component edge. The element’s background extends through the padding, and padding contributes to the box’s size according to box-sizing.

.card {
  border: 1px solid #ccd2dc;
  padding: 1.25rem;
  background: #fff;
}

Margin: space around one element

Choose margin when the spacing should belong to an individual element relative to surrounding content. For instance, a heading may have a bottom margin before the paragraph that follows it.

.article-title {
  margin-block-end: 1rem;
}

Logical properties such as margin-block-end and padding-inline describe flow-relative directions. They can be easier to maintain than physical directions such as margin-bottom when writing direction or text flow can change.

Gap: gutters between layout items

Choose gap when a layout container should set spacing between its items. It works with grid, flex, and multi-column layout. One value sets both row and column gaps; two values set row gap first, then column gap.

.card-list {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 1rem;
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 0.75rem;
}

/* Two values: row gap, then column gap. */
.gallery {
  display: grid;
  gap: 1.5rem 1rem;
}

Gap adds gutters between items without adding a gutter at the outside edges of the container. If the outer edges also need space, give the container padding.

3. Margin collapsing: why vertical margins may not add up

In block layout, adjoining vertical margins can collapse: instead of being added, they combine into one margin. When both margins are positive, the resulting collapsed margin is generally the larger one. So a block with margin-bottom: 24px followed by one with margin-top: 16px may have 24px between them, not 40px.

Collapsing can also happen between a parent and descendant in certain conditions. It does not happen for margins between flex or grid items, and the behavior has exceptions, including floated and absolutely positioned elements. See MDN’s guide to mastering margin collapsing.

For sibling spacing in a flex or grid layout, container gap expresses a gutter directly and avoids block-flow margin collapsing. If a margin seems to disappear or be smaller than expected, check whether it is adjoining another vertical margin and whether a parent-child margin is involved.

4. A practical way to choose

  1. Does the content need room from its component edge? Use padding.
  2. Does one element need space outside its border? Use margin.
  3. Should a layout container space all its neighboring items? Use gap.
  4. Does the component also need outside separation? Combine internal padding with a parent gap or suitable margin, according to who should own each space.
  5. Is the measured size surprising? Check box-sizing, plus the padding and border included in the dimensions.
  6. Is vertical space surprising in block flow? Check for margin collapsing.

5. Runnable example: put the choices together

Save this as an HTML file and open it in a browser. The cards use internal padding, the grid owns the gutters, and the page uses a max-width and centered auto margins.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>CSS spacing example</title>
  <style>
    *,
    *::before,
    *::after {
      box-sizing: border-box;
    }

    body {
      margin: 0;
      padding: 2rem;
      font: 1rem/1.5 system-ui, sans-serif;
      background: #f4f6fa;
      color: #18202b;
    }

    main {
      max-width: 60rem;
      margin-inline: auto;
    }

    h1 {
      margin-block: 0 1rem;
    }

    .cards {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(min(100%, 15rem), 1fr));
      gap: 1rem;
    }

    .card {
      padding: 1.25rem;
      border: 1px solid #ccd2dc;
      border-radius: 0.5rem;
      background: white;
    }

    .card h2 {
      margin-block: 0 0.5rem;
      font-size: 1.1rem;
    }

    .card p {
      margin: 0;
    }
  </style>
</head>
<body>
  <main>
    <h1>Spacing belongs to different boxes</h1>
    <section class="cards" aria-label="Spacing examples">
      <article class="card">
        <h2>Padding</h2>
        <p>Space between this text and the card border.</p>
      </article>
      <article class="card">
        <h2>Grid gap</h2>
        <p>Space between sibling cards is set by their grid container.</p>
      </article>
    </section>
  </main>
</body>
</html>

6. Debug spacing in browser developer tools

Browser developer tools can show an element’s content dimensions, padding, border, and margin in a box-model view. MDN’s box model learning guide describes how to inspect these values.

  1. Select the element that appears misplaced.
  2. Inspect its box model and computed styles. Check margin, padding, border, width, height, and box-sizing.
  3. Inspect its parent’s layout mode: normal block flow, flex, grid, or multi-column.
  4. For a flex or grid layout, inspect gap, child margins, and alignment such as justify-content or align-content.
  5. Change one source of spacing at a time, then inspect again. Several rules can contribute to the same visible distance.

7. Troubleshooting common spacing problems

What you see Likely cause What to check or change
Two vertical margins seem to produce less space than their sum Adjoining block margins collapsed Check the adjoining margins and layout context. Use a flex/grid container with gap when the spacing belongs between its items.
A box is wider or taller than its declared size content-box adds padding and border outside the declared content dimensions Inspect box-sizing; use border-box if the authored dimensions should include padding and border.
There is space around the whole group as well as between items Container padding or child margins add to the gaps Inspect the container’s padding and each item’s margins. Gap alone does not create outer-edge gutters.
The visible distance between items is larger than gap Margins, padding, or distributed alignment also add space; grid alignment can enlarge separation between tracks Inspect item margins, container padding, and alignment rules along with gap.
A child’s top margin seems to move the parent too A parent and descendant margin may collapse under the applicable block-flow conditions Inspect the parent and child together. Decide which box should own the spacing and apply padding or a layout approach that expresses that ownership.
Gap appears to do nothing The element may not be a grid, flex, or multi-column container, or the items may not create separate tracks/columns Inspect the computed display mode and the container’s children.
There is no space between items A later or more specific rule may override the gap, or the container has no effective item separation Inspect computed row-gap and column-gap, the cascade, and the container layout.

8. Performance, reliability, and cost

Margin, padding, and gap are browser layout properties; this guide makes no version-specific compatibility claim. For compatibility needs, check current browser support for the exact property and layout combination in your target browsers. For reliable spacing, assign each distance to one clear owner and inspect the computed layout rather than stacking adjustments without checking their combined effect.

There is no external service cost to using these CSS properties. If you need a rendered screenshot of a page to inspect spacing, you can use a local browser workflow or a screenshot API. ScreenshotNeo is a website screenshot API and MCP server for developers: ScreenshotNeo. Its API can capture a page, but it does not replace inspecting computed CSS when diagnosing the source of a spacing issue.

9. Or skip the browser setup

Capture a page with one GET request. See the ScreenshotNeo API documentation for the options and response details.

curl -G "https://api.screenshotneo.com/v1/shot" \
  -d access_key=YOUR_API_KEY \
  --data-urlencode url=https://stripe.com \
  -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
await Bun.write('shot.webp', res);

ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before the shot. Bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Only clean shots are billed, and responses report the page verdict and billing status in headers.

Sign up for 1,000 free screenshots a month, with no card.

10. FAQ

Should I use margin or gap between cards?

When a grid or flex container owns the spacing between its items, use gap. Use margins when spacing belongs to individual elements or when the elements are not arranged as items in such a container.

Does padding count toward width?

With content-box, padding adds to the declared width. With border-box, padding is included in the declared width. Margin is outside the border in both cases.

Can a component use both padding and gap?

Yes. Padding can separate content from a component’s edge, while a parent’s gap separates that component from sibling items.

Why is the space between grid items larger than the gap value?

Child margins, container padding, or distributed alignment can add visible distance. Inspect those rules together with the grid’s gap.