DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk4 min

CSS Margins: How to Set and Adjust Spacing

CSS margins set space outside an element’s border. Learn shorthand mapping, alignment with auto, logical properties, and why adjacent vertical margins can collapse.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the CSS margin property to control space outside an element’s border. One to four values set the sides in a predictable order; use a side-specific or logical property when you need more control. If adjacent vertical margins seem not to add up, they may be collapsing.

What CSS margins control

A margin is the area outside an element’s border. Padding is inside the border, between the border and the content. Use margin to position a box relative to surrounding content; use padding when you want space within the box itself. The W3C CSS Box Model Level 3 defines margin as part of the box model.

As an Amazon Associate I earn from qualifying purchases.

Set margins with the shorthand

The margin shorthand sets all four physical sides. Values are lengths, percentages, auto, or negative values. The order for four values is top, right, bottom, left.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
.card {
  margin: 1rem;                 /* all four sides */
  margin: 1rem 2rem;            /* top/bottom, left/right */
  margin: 1rem 2rem 3rem;       /* top, left/right, bottom */
  margin: 1rem 2rem 3rem 4rem;  /* top, right, bottom, left */
}

With one value, every side gets that value. With two, the first applies to top and bottom and the second to left and right. With three, the first is top, the second applies to both horizontal sides, and the third is bottom. With four, values proceed clockwise from top. These rules are specified in CSS 2.2’s margin property reference.

Adjust one side

Use margin-top, margin-right, margin-bottom, or margin-left when a particular physical side needs a different value:

.notice {
  margin-top: 1rem;
  margin-bottom: 2rem;
}

Use auto margins for alignment

auto is resolved by the layout algorithm; it is not a fixed spacing amount. In common block layouts, automatic inline margins can center a box when it has a constrained width:

.content {
  width: min(100% - 2rem, 65rem);
  margin-left: auto;
  margin-right: auto;
}

For flow-relative alignment, margin-inline: auto is often a better fit. The result depends on the formatting context and available space, so auto does not center every kind of element in every layout.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Percentages and negative values

Under CSS 2.2’s margin rules, percentages—including top and bottom margins—are calculated from the containing block’s width, not its height. This can make a vertical percentage margin larger or smaller than expected when the container’s height changes. Negative margins are allowed and can pull boxes closer together or make them overlap; use them deliberately and check how the surrounding layout responds.

Why vertical margins may not add together

In relevant block layout, adjoining vertical margins can collapse into one margin instead of being added. A frequent case is the bottom margin of one in-flow block sibling adjoining the top margin of the next. A parent’s margin can also collapse with the margin of its first or last in-flow child in specified circumstances. See MDN’s guide to margin collapsing for the common cases and exceptions.

How the collapsed result is determined

  • When two positive adjoining margins collapse, the gap is the larger margin, not their sum.
  • When positive and negative margins collapse together, the largest negative magnitude is deducted from the largest positive margin.
  • When all adjoining margins are negative, the most negative value determines the result.

Debug an unexpected gap

  1. Inspect the computed margin-top and margin-bottom values on both neighboring blocks in your browser’s developer tools.
  2. Check that the elements are in normal block flow and that the margins are adjoining. Horizontal margins do not collapse.
  3. Look for a border, padding, inline content, clearance, or formatting-context boundary that may prevent adjoining margins from collapsing.
  4. Check the element types and container layout. Margins of floats, absolutely positioned boxes, and inline-block boxes do not collapse in the described cases; flex and grid containers do not collapse margins between their items.

Do not assume all vertical margins collapse: the behavior applies only to adjoining margins in relevant block layout. If you need a consistent gap between children, consider gap on a flex or grid container. A gap belongs to the container’s spacing between items; a margin belongs to an individual element’s outside edge.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose physical margins, logical margins, or gap

Approach Best fit Tradeoff
margin shorthand Setting several or all sides concisely Less explicit when each side has a distinct purpose
Physical longhands such as margin-left A layout deliberately tied to top, right, bottom, and left Does not adapt semantically to writing direction
Logical properties such as margin-inline-start Reusable interfaces for different text directions or writing modes Requires understanding block and inline axes
gap in flex or grid Consistent spacing between layout items Controls spacing between container items, not the outside edge of an individual element

Use logical properties for flow-relative layouts

Physical properties name fixed sides; logical properties name sides relative to text flow. margin-inline-start means the start side of the inline axis. margin-block sets the block-start and block-end margins. Their physical mapping depends on writing mode and directionality. W3C’s CSS Box Model Level 4 describes the flow-relative model.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
.article {
  margin-block: 1.5rem;
  margin-inline: auto;
  max-inline-size: 65ch;
}

Prefer logical properties for components that should adapt to right-to-left text or vertical writing modes. Physical properties are appropriate when the design intentionally refers to a fixed screen edge and its writing-mode assumptions are clear.

Or skip the browser setup

If you need a screenshot of the rendered result, ScreenshotNeo is a website screenshot API and MCP server for developers. Here is a one-request cURL example:

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

See the ScreenshotNeo documentation for request options. It removes cookie banners, popups, and chat widgets before capture; 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 a month with no card; paid plans start at $5 for 3,000. Sign up for free.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.