ScreenshotNeo

BlogGuides

CSS Margins: How to Set and Adjust Spacing

Learn CSS margin shorthand, side-specific and logical properties, centering with auto, and how to diagnose margin collapse.

By the ScreenshotNeo team4 October 20266 min read

Use CSS margin to create space outside an element’s border. Set all four sides with the shorthand, target one side with a longhand, and use logical properties when spacing should follow text direction. If two vertical margins appear not to add together, check for margin collapse: adjoining margins in block layout can combine into one gap.

For example, this gives a card one rem of space on every side:

.card {
  margin: 1rem;
}

1. What margin does

The CSS box model places margin outside the border. Padding is inside the border, between the border and content. Use margin to space a box from surrounding content; use padding to add room inside the box around its content. W3C CSS Box Model and MDN’s box model guide describe these areas.

.notice {
  margin: 1rem;  /* space outside the border */
  padding: 1rem; /* space inside the border */
  border: 1px solid #777;
}

Margins are transparent and do not form part of the element’s painted background. A margin can be positive, zero, negative, a length, a percentage, or auto, subject to the layout rules for the element. Percentages—including top and bottom margin percentages—are based on the containing block’s width under CSS 2.2. CSS 2.2 margin properties

2. Set margins with shorthand or longhands

The margin shorthand accepts one to four values. Values map clockwise from the top, with omitted sides filled from the corresponding value:

Values Mapping
margin: 1rem All four sides: 1rem
margin: 1rem 2rem Top and bottom: 1rem; left and right: 2rem
margin: 1rem 2rem 3rem Top: 1rem; left and right: 2rem; bottom: 3rem
margin: 1rem 2rem 3rem 4rem Top: 1rem; right: 2rem; bottom: 3rem; left: 4rem

Use physical longhands when you need to name a specific screen side:

.card {
  margin-top: 1rem;
  margin-right: 2rem;
  margin-bottom: 1.5rem;
  margin-left: 2rem;
}

The shorthand is compact when sides share values. Longhands make individual adjustments explicit. Remember that a later shorthand declaration resets all four margins, including any earlier longhand values:

.card {
  margin-left: 2rem;
  margin: 1rem; /* also resets margin-left to 1rem */
}

3. Use auto to center a block

In a common block layout, a block with a constrained width can be centered by giving its left and right margins auto. The browser resolves auto using the layout algorithm and available space; it is not a fixed amount of spacing.

.article {
  width: min(100% - 2rem, 65ch);
  margin-inline: auto;
}

Here the width is constrained and the inline margins share the remaining available space. The precise result depends on the formatting context and available space, so auto does not center every kind of element in every layout. For a fixed physical left/right layout, margin-left: auto; margin-right: auto; is a familiar alternative.

4. Choose physical or logical properties

Physical properties such as margin-left name a fixed side. Logical properties name a side in relation to the writing mode and text direction: inline follows the line of text, while block follows the direction blocks are stacked. For example, inline start is typically left in left-to-right text and right in right-to-left text.

.article {
  margin-block: 1.5rem;       /* block start and end */
  margin-inline: auto;        /* inline start and end */
  max-inline-size: 65ch;
}

.label {
  margin-inline-start: 0.5rem;
}

Use logical properties for reusable components that may appear in right-to-left content or vertical writing modes. Use physical properties when the design deliberately refers to a fixed screen edge. The W3C CSS Box Model Level 4 describes flow-relative properties; see also MDN’s margin-block reference.

5. Understand margin collapse

Adjoining vertical margins of in-flow block boxes can collapse into one margin instead of adding together. The common case is the bottom margin of one block sibling next to the top margin of another. If those margins are both positive, the resulting gap is the larger margin.

.first {
  margin-bottom: 24px;
}

.second {
  margin-top: 16px;
}
/* In the common adjoining block-sibling case, the gap is 24px, not 40px. */

Collapse can also occur between a parent and its first or last in-flow child when the required conditions hold. It does not mean all vertical margins collapse: the margins must be adjoining in a relevant block layout. Horizontal margins do not collapse. Floats, absolutely positioned boxes, and inline-block boxes do not collapse in the cases described by MDN; flex and grid containers also do not collapse margins between their items. Consult MDN’s margin-collapsing guide and the detailed CSS 2.2 rules for conditions and edge cases.

When positive and negative adjoining margins collapse, the largest negative magnitude is deducted from the largest positive margin. When all adjoining margins are negative, the most negative value controls. Negative margins are allowed, but they can cause overlap, so inspect the resulting layout rather than assuming they create an ordinary gap.

Debug a gap that looks too small

  1. Inspect the computed margin-bottom of the first block and margin-top of the next in browser developer tools.
  2. Check whether both boxes participate in normal block flow and whether the margins are adjoining.
  3. Look for borders, padding, inline content, clearance, or a formatting-context boundary that may prevent or change collapse.
  4. Check parent-child margins as well as sibling margins.
  5. If the desired spacing is consistently between flex or grid items, use the container’s gap property. Use margin when the spacing belongs to an individual element’s outside edge.

6. Pick the right spacing tool

Approach Good fit Tradeoff
margin shorthand Several sides share a value Different side purposes may be less obvious
Physical longhands A fixed top, right, bottom, or left adjustment Does not adapt semantically to writing direction
Logical margins Reusable interfaces across writing modes and directions Requires thinking in block and inline axes
gap in flex or grid Consistent spacing between layout items Sets spacing between container items, not an individual item’s outer edge

7. Common problems and fixes

Symptom Likely cause Fix
Vertical spacing is smaller than the two declared values added together Adjoining block margins collapsed Confirm the computed margins and collapse conditions. Use flex/grid gap when spacing belongs between items.
margin: 1rem 2rem changes the wrong sides The two-value shorthand means block sides first, inline sides second in horizontal writing Use longhands or logical properties when the intended side mapping needs to be unmistakable.
A later rule seems to erase one side’s margin A shorthand declaration resets all four sides Move the shorthand before the side-specific override, or write the complete intended shorthand.
margin-inline: auto does not center the element The element may not have a constrained width, or its layout context may resolve auto margins differently Constrain its inline size and check its formatting context and available space.
A vertical percentage margin is unexpectedly large or small Percentage margins use the containing block’s width under CSS 2.2, not its height Use an appropriate length or another sizing approach if the desired value should track height.
Margins do not create space in the direction expected in an RTL or vertical layout A physical property names a fixed side Use the corresponding logical property, such as margin-inline-start.
Negative margin causes overlap A negative margin pulls the box toward adjacent content Reduce or remove the negative value and inspect both adjacent boxes and responsive sizes.

8. Or skip the browser setup

If you need a screenshot of the page after adjusting CSS, ScreenshotNeo can return an image or PDF with one API request. See the ScreenshotNeo API documentation.

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

Before capture, ScreenshotNeo accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers report the page verdict and billing status. Its MCP server lets AI agents use take_screenshot, get_page_info, and capture_pdf. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots. Every feature is on every plan. Learn about ScreenshotNeo, then sign up for 1,000 free screenshots a month with no card.

9. FAQ

Can a margin be negative?

Yes. Negative values are permitted and can pull boxes toward neighboring content. Check for overlap at different viewport sizes.

Are margin and padding interchangeable?

No. Margin is outside the border; padding is inside it. Choose based on which edge should own the space.

Why do vertical margin percentages use width?

CSS 2.2 defines margin percentages against the containing block’s width, including top and bottom margins. Avoid relying on a vertical percentage when you intend to track the containing block’s height.

Should I use margin or gap between cards?

Use gap when the spacing belongs to the relationship between items in a flex or grid container. Use margin when an individual card needs space outside its own edge.