ScreenshotNeo

BlogGuides

CSS Box Model: A Guide to Margin, Border, Padding, and Content

Understand how content, padding, border, and margin determine an element’s size—and why its rendered width can exceed its CSS width.

By the ScreenshotNeo team4 October 20268 min read

The CSS box model describes an element as nested rectangular areas: content → padding → border → margin. With the default box-sizing: content-box, a declared width measures content only, so padding and border make the rendered border box wider. With box-sizing: border-box, the declared width includes content, padding, and border. Margin remains outside the border in both models.

If an element appears wider than its CSS width, check its box-sizing, horizontal padding, and border first. For example, a 350px content width with 25px padding and a 5px border on each side has a 410px border-box width, plus any margin outside it. MDN’s box-model guide illustrates this calculation.

1. The four layers, from inside out

Every element generates boxes that determine its size and spacing. Think of the layers as rectangles surrounding one another:

  1. Content: The area for text, images, or other material. For a normal block element, the content width is affected by its containing layout and its sizing rules.
  2. Padding: Space between the content and the border. A background color or image extends through the padding area.
  3. Border: The edge drawn around the padding and content.
  4. Margin: Space outside the border that separates the element from other boxes. A background does not paint the margin.

Padding is inside the border; margin is outside. Neither sizing model changes that order. See MDN’s CSS box model reference for the layer definitions.

2. Why an element is wider than its CSS width

The default value of box-sizing is content-box. Under that model, width sets the content area. Horizontal padding and border are added to the outside to produce the border-box width.

.card {
  box-sizing: content-box;
  width: 350px;
  padding: 0 25px;
  border: 5px solid #333;
}

The arithmetic is:

content width                 350px
left and right padding       + 50px  (25px + 25px)
left and right border        + 10px  (5px + 5px)
                              ------
border-box width               410px
margin                     outside that 410px

This is the border box, not the element’s full outside spacing: margins lie beyond it. MDN’s worked example uses the same dimensions and arrives at a 410px border box. Source: MDN, “The box model.”

Calculate a content-box element’s outer border-box size

For a box with definite width and height, add both sides of each relevant layer:

border-box width  = content width
                  + padding-left + padding-right
                  + border-left-width + border-right-width

border-box height = content height
                  + padding-top + padding-bottom
                  + border-top-width + border-bottom-width

To estimate the space needed in the layout, account for margins separately. Do not simply add both margins in every layout: adjacent vertical margins can collapse, and layout modes such as flexbox and grid handle margins differently.

3. content-box and border-box compared

Model What declared width and height measure What is added outside that measurement Where margin sits
content-box (default) Content area Padding and border Outside the border box
border-box Content, padding, and border together Nothing from padding or border Outside the border box

With border-box, padding and border still exist. They use space inside the declared dimensions, leaving less room for content. For example, a 350px-wide border-box with 25px padding and a 5px border on both sides leaves 290px for content.

.card {
  box-sizing: border-box;
  width: 350px;
  padding: 0 25px;
  border: 5px solid #333;
}

The box-sizing specification describes how the content box is derived when padding and border are included in the specified size. If they consume more than that size, the content dimension cannot be negative; it is floored at zero. See the CSS Working Group’s CSS Box Sizing Module Level 3 draft.

4. Use border-box for predictable component sizing

Many stylesheets apply border-box broadly so that a declared width corresponds to the visible border-box width. A common reset is:

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

Some projects set it on the root and inherit it, leaving components able to override it:

html {
  box-sizing: border-box;
}

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

Choose and document a consistent convention. Applying border-box can change existing layouts that relied on content-box dimensions, so inspect components with fixed widths, padding, or borders when adopting the reset. It does not include margin.

5. Set each layer with CSS

Width and height

width and height set dimensions according to the selected box-sizing model. Values such as percentages are resolved against the containing block according to the property’s rules. In flexible or grid layouts, available space and track sizing also affect the final rendered dimensions. min-width, max-width, min-height, and max-height constrain the result.

Padding

Use the shorthand to set one to four sides:

padding: 12px;            /* all four sides */
padding: 8px 16px;        /* top/bottom, left/right */
padding: 4px 12px 20px;   /* top, left/right, bottom */
padding: 4px 8px 12px 16px; /* top, right, bottom, left */

Individual properties include padding-top, padding-right, padding-bottom, and padding-left. Logical properties such as padding-inline and padding-block express spacing relative to writing direction and are useful for multilingual layouts.

Border

Set border width, style, and color with the shorthand, or use side-specific and longhand properties:

border: 1px solid #ccc;
border-left: 4px solid teal;
border-width: 1px 2px;
border-style: solid;
border-color: #ccc;

A border with border-style: none does not draw a border; its used border width is zero. Remember that borders on both horizontal sides contribute to a content-box element’s border-box width.

Margin

Margin shorthands follow the same one-to-four-value ordering as padding. A common centering pattern for a block with a constrained width is:

.container {
  width: min(100% - 2rem, 70rem);
  margin-inline: auto;
}

Auto margins can distribute available space in applicable layouts. Margins can also be negative, which may cause boxes to overlap or shift; padding cannot be negative. Margins are transparent, and adjacent vertical margins can collapse in some block formatting contexts.

6. Margin collapsing and the gap between boxes

In normal block flow, adjacent vertical margins may collapse into one shared margin. For two positive adjacent margins, the resulting gap is generally the larger margin rather than their sum. A positive and a negative margin combine differently. Horizontal margins do not collapse in the same way.

Margin collapsing has conditions and exceptions. It can occur between adjacent in-flow block siblings, between a parent and its first or last in-flow child in some circumstances, and between a box’s own adjoining margins in some circumstances. Borders, padding, inline content, clearance, and formatting-context boundaries affect whether collapse occurs. Flex and grid items do not collapse margins with one another. For the full conditions, use MDN’s box-model guide.

If a layout’s spacing is difficult to reason about, use gap on a flex or grid container for space between its items:

.row {
  display: flex;
  gap: 1rem;
}

gap controls inter-item spacing in supported layouts and is not a margin on each child.

7. Inspect the actual box in browser developer tools

  1. Select the element in the Elements or Inspector panel.
  2. Open the computed styles and box-model diagram. Compare content, padding, border, and margin values.
  3. Check the computed box-sizing, not just the rule you expected to apply. A later or more specific rule may override it.
  4. Inspect the parent width, grid tracks, flex sizing, and min/max constraints if the computed box differs from the available space.
  5. Temporarily toggle padding, border, or width declarations to identify which layer causes the excess.

For a programmatic check in a browser console, getBoundingClientRect() returns the element’s border-box dimensions (including transforms); it does not add margins. Computed styles expose the box-sizing and side values:

const element = document.querySelector('.card');
const rect = element.getBoundingClientRect();
const style = getComputedStyle(element);

console.log({
  boxSizing: style.boxSizing,
  renderedBorderBoxWidth: rect.width,
  renderedBorderBoxHeight: rect.height,
  paddingLeft: style.paddingLeft,
  paddingRight: style.paddingRight,
  borderLeft: style.borderLeftWidth,
  borderRight: style.borderRightWidth,
  marginLeft: style.marginLeft,
  marginRight: style.marginRight
});

8. Troubleshooting common sizing problems

Symptom Likely cause What to check or change
A 350px element renders 410px wide Content-box plus 25px padding and 5px border on both sides Use box-sizing: border-box if 350px should include padding and border, or reduce the content width.
A border-box element’s content is unexpectedly narrow Padding and border consume part of its declared size Reduce the inner spacing, increase the outer declared size, or allow the element to grow.
Width exceeds the parent even with border-box Minimum sizing, a long unbreakable string, fixed child width, grid track, or flex constraints Inspect the child and parent sizing rules. Consider min-width: 0 on a flex or grid item when its automatic minimum size prevents shrinking; add suitable wrapping for long content.
The visible gap is not the sum of two margins Vertical margin collapse or a layout mode with its own spacing behavior Check normal block flow and parent formatting context. Use container gap for flex/grid item spacing when appropriate.
Changing width has no apparent effect A min/max constraint, intrinsic sizing, or layout algorithm controls the used size Inspect computed min/max values and the containing layout; check whether the element is a flex or grid item.
A background color seems to stop before the margin Margins are outside the painted background area Use padding for colored space inside a component, or style the parent if the outside region should be colored.
A reset did not change one component A more specific rule or later declaration overrides it, or the selected node is a pseudo-element Inspect computed box-sizing and include pseudo-elements in a global reset if needed.
A specified border width does not affect size The border style is none or hidden Set a visible border style such as solid if a border is intended.

9. Practical checklist

  • Is the element using content-box or border-box?
  • For content-box, did you add both horizontal padding values and both horizontal border widths?
  • Are you keeping margin separate from the border-box dimensions?
  • Could vertical margin collapsing explain the observed gap?
  • Are min/max sizes, intrinsic content, or parent layout constraints changing the used size?
  • Did you verify the computed values in developer tools?

10. Or skip the browser setup

If documenting a layout means you need a screenshot of a page or component, you can capture it with a website screenshot API instead of setting up a browser script. ScreenshotNeo is a website screenshot API and MCP server. It can capture a page or a CSS-selected element, so you can save the whole page or focus on a box-model example.

One GET request returns an image or PDF. Here is the cURL example from 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

Cookie banners are accepted and removed before capture, along with known newsletter popups and chat widgets. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed; response headers identify the page verdict and billing status. The MCP server offers take_screenshot, get_page_info, and capture_pdf for AI agents. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000.

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

11. Frequently asked questions

Does box-sizing affect margin?

No. It determines whether the declared width and height include padding and border. Margin remains outside the border box.

Does border-box include an outline?

No. An outline is drawn outside the border but does not take up space in the box model’s border-box dimensions.

Can width be larger than the parent even with border-box?

Yes. For example, a minimum size, unbreakable content, or layout constraints can make an element overflow. border-box only changes what the declared width includes.

Is margin part of an element’s measured width?

Not in the border-box width returned by getBoundingClientRect(). Margin is separate outside spacing and must be considered separately when reasoning about layout.

References