Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

CSS  Module 4 – The box model, sizing and overflow

The box model: content, padding, border, margin

How CSS box sizes combine content, padding, border and margin: content-box or border-box, percentage padding, inline painting and focus rings.

  • Beginner
  • 25 minutes
  • Examples run with Node.js 24.21.0 and quickjs 0.32.0
  • By MySmartCoPilot
Free lesson, Pro answers: 25 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Identify the content, padding, border and margin areas of a box in DevTools
  • Choose between content-box and border-box sizing and apply border-box to a whole project
  • Predict what percentage padding and padding on inline elements do to the layout
  • Draw focus rings with outline and box-shadow without changing layout

A card with width: 300px can occupy 350 px once its padding and border are included. A generated CSS box has four areas. In the middle is the content: text, an image or child boxes. Around it comes the padding, then the border, and outside the border the margin, which keeps neighbours at a distance. The width and height you write size only the content unless you change box-sizing, so a card with width: 300px, 24 px of padding and a 1 px border is drawn 350 px wide. Knowing which layer each property sets is what lets you hit the sizes in a design, space things predictably and draw focus rings that move nothing.

This lesson takes the same card through all four areas. The editable JavaScript computes its sizes; the complete HTML fixtures let you inspect layout, font-dependent painting and focus in your own browser.

Four edges measure different parts of the same card

Follow the card from its 300 px content to its outer margin edge. The static diagram keeps every area visible at once:

The four areas of a box

Four nested boxes of a 300 px card: content 300 px, padding box 348 px, border box 350 px and margin box 382 px wide.margin box: 382 px16 px margin, transparentborder box: 350 px (offsetWidth)1 px borderpadding box: 348 px (clientWidth)24 px paddingcontent box: 300 pxwidth sets this box(box-sizing: content-box)

The four areas of one box, with the widths of the lesson's card

Text description of the diagram

The diagram shows the card from the lesson, styled with width: 300px, padding: 24px, border: 1px and margin: 16px, and the default box-sizing: content-box. Four boxes sit one inside the other.

  1. The outermost box, drawn with a dashed line, is the margin box: 382 px wide, because it adds 16 px of margin on each side. Margins are always transparent.
  2. Inside it is the border box: 350 px wide, with 1 px of border on each side. This is the width offsetWidth reports.
  3. Inside the border is the padding box: 348 px wide, with 24 px of padding on each side. The element's background shows through here. This is the width clientWidth reports when there is no scrollbar.
  4. The innermost box is the content box: 300 px wide. Under content-box, width: 300px sets this box, so the padding and the border are added outside it.
  • Content is where the text or the image goes. The content box: The inner box containing an element’s text, child boxes or replaced content, before surrounding padding, border and margin. is its rectangle; under the default sizing, width and height set its size.
  • Padding is the space between the content and the border. It belongs to the element, so the background colour or image shows through it, and it can’t be negative.
  • Border is the line drawn around the padding. The border box: The box enclosed by the border’s outer edges, including content and padding but excluding the surrounding margin. includes that border, whose width takes up space just as padding does.
  • Margin is the space outside the border. It is always transparent, it can be negative to pull boxes closer, and adjoining block-axis margins can merge; those are top/bottom margins in the horizontal-writing fixtures, which the next lesson covers.

Each layer ends at an edge, and each edge encloses a box: the content box, the padding box, the border box and the margin box. Browsers report the border box as the element’s size in most places, so that is the number to check first. The CSSOM gives you two quick measurements: offsetWidth is the width of the border box and clientWidth the width of the padding box without any scrollbar, both as whole numbers of pixels, while getBoundingClientRect() keeps the fractions. For this single, untransformed card those readings describe the expected edges. An inline element may have several fragments, and a transform affects its bounding rectangle without changing offsetWidth; an element that generates no box reports no such layout width.

Step outwards one area at a time. Before advancing, add the two sides of the area that is about to appear:

Interactive · stage by stage From 300 px of content to a 382 px margin box Advance one edge at a time; add the room on both sides before revealing the next box.
From 300 px of content to a 382 px margin box, step 4 of 4. Showing Content (300 px), Padding edge (300 + 48 = 348 px), Border edge (348 + 2 = 350 px), Margin edge (350 + 32 = 382 px). In focus: Margin edge.Content300 pxPadding edge300 + 48 = 348 pxBorder edge348 + 2 = 350 pxMargin edge350 + 32 = 382 px

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. Start with the content. The card uses content-box sizing and width: 300px. Begin with 300 px of content; no padding, border or margin has been added to this width.
  2. Add both padding sides. Each side has 24 px of padding. Add 48 px altogether: the padding edge encloses 348 px, before any border or margin.
  3. Add the border. The two 1 px borders add another 2 px. The border-box width is 350 px; this is offsetWidth for the fixture with no transform or scrollbar.
  4. Keep margin outside. Two 16 px margins add 32 px outside the border. The outer margin box is 382 px wide, but offsetWidth stays 350 px and the margin has no background paint.

The border edge is 50 px beyond the content width, whereas the extra 32 px of margin belongs outside the border. Do not count that transparent margin as part of offsetWidth.

Checkpoint

Check: Content, padding, border and margin edges

  1. Question 1 of 2 The content-box card has 300 px content, 24 px padding per side and 1 px borders. What width reaches its border edge?

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 350 px

    Add both padding sides and both borders: 300 + 48 + 2 = 350 px. Margin is outside that measurement.

  2. Question 2 of 2 You add 16 px margins on both sides of that 350 px border box. Which statement describes the change?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: The margin box becomes 382 px; the border box stays 350 px.

    The outer footprint includes margin, while border-box measurements and background paint stop before that margin.

To see the four areas of any element, select it in DevTools. The current Chrome documentation places its box-model diagram in the Styles sidebar; Firefox documents its Box Model view, and WebKit documents the Computed panel. In those inspectors, hovering over the element’s markup shades its content, padding and margin on the page. The values in the diagram can be edited in place, which is the quickest way to try a spacing change.

Choose the box that a written size describes

Three cards share width, 24 px of padding and a 1 px border, and differ only in box-sizing. The script at the end prints the layout readings for the browser in which you open the file:

content-box or border-box

Three cards, measured HTML · box-sizing.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>content-box and border-box</title>
  <style>
    body { font: 16px/1.5 system-ui, sans-serif; margin: 16px; }
    .card {
      width: 300px;
      padding: 24px;
      border: 1px solid #555;
      margin-block-end: 16px;
    }
    .border-box { box-sizing: border-box; }
    .too-narrow { box-sizing: border-box; width: 40px; }
  </style>
</head>
<body>
  <div class="card" id="a">content-box, the default</div>
  <div class="card border-box" id="b">border-box</div>
  <div class="card too-narrow" id="c">40</div>
  <script>
    // offsetWidth is the border box; clientWidth is the padding box (minus any scrollbar).
    for (const id of ['a', 'b', 'c']) {
      const el = document.getElementById(id);
      console.log(`${id}: width ${getComputedStyle(el).width}, border box ${el.offsetWidth}px, padding box ${el.clientWidth}px`);
    }
  </script>
</body>
</html>

Cards a and b are width: 300px and card c is width: 40px. The sizing rules give these border-box and padding-box widths for the fixture, with no scrollbar or transform:

Card Border box Padding box
a, content-box 350 px 348 px
b, border-box 300 px 298 px
c, border-box, 40px 50 px 48 px

Under content-box, the default, width is the content width, and the padding and border of both sides are added outside it: 300 + 2 × 24 + 2 × 1 = 350. Under border-box, width is the border box, and the content gets what is left: 300 − 50 = 250 px. That is the size a designer means, which is why most projects switch to it.

Card c shows the lower bound that border-box cannot remove. Padding and border can’t be squeezed, and the content box can’t go below zero, so a 40 px border-box card with 50 px of padding and border is drawn 50 px wide. getComputedStyle() reports the used width in the same terms: the expected readings are 300px for both a and b, and 50px for c.

Compare a, b and c in the scene. Keep the 50 px of padding and border fixed, and predict the content width before each step:

Interactive · stage by stage Three requests share 50 px of padding and border Compare the content-box, border-box and too-small border-box requests without changing the two-sided room.
Three requests share 50 px of padding and border, step 5 of 5. Showing Written width (c: border-box, 40 px), Padding and border (2 × (24 + 1) = 50 px), Content width (max(0, 40 − 50) = 0), Border-box width (50 px). In focus: Border-box width.Written widthc: border-box, 40 pxPadding and border2 × (24 + 1) = 50 pxContent widthmax(0, 40 − 50) = 0Border-box width50 px

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. Card a requests content. Card a writes 300px with content-box. Its 24 px padding and 1 px border on each side need 50 px outside the requested content.
  2. Card a becomes 350 px. Keep the content at 300 px and add 50 px. The border box is 350 px and the padding box, before the two borders, is 348 px.
  3. Card b requests the border. Card b uses border-box with the same written 300 px. The 50 px of padding and border is included, leaving 250 px for its content.
  4. Card c cannot squeeze room. Card c asks for a 40 px border box. Subtracting the 50 px room would make content negative, so content floors at zero and the border box is 50 px.
  5. Margins remain outside. Changing box-sizing never includes margins in that requested width. The card program adds 16 px on each side only after it has computed the border box.

The 40 px request does not fit even empty content: its border box is still 50 px. The same sums appear in the editable program below; change the card width to 40 and run it to compare both sizing choices:

The four boxes of the card JavaScript · box_model.mjs
// The box model as arithmetic: the width of each of the four boxes of an element, from the lengths in its CSS
// (all in px). Change the numbers and run it again. This is the fixed-length, horizontal card model, not a DOM
// measurement or a complete layout algorithm for every kind of element.

/** The four boxes of one element along one axis. */
function boxes({ width, padding, border, margin, boxSizing }) {
  const sides = 2; // left and right (top and bottom work the same way)
  const around = (padding + border) * sides;
  // border-box: the width you write includes padding and border, and the content box is never below 0.
  const content = boxSizing === 'border-box' ? Math.max(0, width - around) : width;
  const paddingBox = content + padding * sides;
  const borderBox = paddingBox + border * sides;
  const marginBox = borderBox + margin * sides;
  return { content, paddingBox, borderBox, marginBox };
}

const card = { width: 300, padding: 24, border: 1, margin: 16 };
console.log('width: 300px; padding: 24px; border: 1px; margin: 16px');
console.log('box-sizing     content  padding  border  margin');
for (const boxSizing of ['content-box', 'border-box']) {
  const b = boxes({ ...card, boxSizing });
  const cells = [b.content, b.paddingBox, b.borderBox, b.marginBox].map((n, i) => String(n).padStart(i < 2 ? 7 : 6));
  console.log(`${boxSizing.padEnd(13)}  ${cells.join('  ')}`);
}

// When padding and border need more room than the width allows, they win and the box grows.
const narrow = boxes({ ...card, width: 40, boxSizing: 'border-box' });
console.log(`border-box, width: 40px -> content ${narrow.content}, border box ${narrow.borderBox}`);

// Percentage padding and margin use the containing block’s inline size, which is its WIDTH in this
// horizontal-writing card model, including for the top and bottom sides.
const percentOf = (percent, containingWidth) => (percent / 100) * containingWidth;
for (const containingWidth of [640, 360]) {
  console.log(`containing block ${containingWidth}px wide: padding-top: 56.25% = ${percentOf(56.25, containingWidth)}px`);
}

Output

width: 300px; padding: 24px; border: 1px; margin: 16px
box-sizing     content  padding  border  margin
content-box        300      348     350     382
border-box         250      298     300     332
border-box, width: 40px -> content 0, border box 50
containing block 640px wide: padding-top: 56.25% = 360px
containing block 360px wide: padding-top: 56.25% = 202.5px

Recorded with Node.js 24.21.0 on macOS 26 arm64. To run it yourself: mise exec node@24.21.0 -- node box_model.mjs

box-sizing changes how definite lengths and percentages in sizing properties are interpreted, including width, height, their min- and max- limits, and flex-basis. Intrinsic keywords do not simply acquire a different content size because box-sizing changes. It never changes margins, which always sit outside the border box.

HTML, CSS & JS Playground (Online Editor) Paste box-sizing.html into the HTML box: the console under the preview prints the widths for your browser.

Border-box for a whole project

border-box everywhere CSS · border-box-everywhere.css
/* One rule for the whole project: width and height include padding and border. */
html {
  box-sizing: border-box;
}

/* Every element and pseudo-element takes its parent's value, so a component that needs content-box can switch its
   own root back, and everything inside it follows. */
*,
*::before,
*::after {
  box-sizing: inherit;
}

box-sizing is not inherited, so the second rule asks every element and pseudo-element to take its parent’s value. The result is border-box everywhere, with one escape hatch: a component that was built for content-box, such as an older widget, gets box-sizing: content-box on its own root, and everything inside it follows. A plain * { box-sizing: border-box; } works too, but then each element inside such a widget needs its own rule.

Checkpoint

Check: What a written size includes

  1. Question 1 of 2 Card c requests width: 40px with border-box, 24 px padding and 1 px border on each side. What border-box width does the sizing model give?

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 50 px

    The padding and borders need 2 × (24 + 1) = 50 px. The content floors at zero, leaving that 50 px lower bound.

  2. Question 2 of 2 Why does the project reset explicitly write box-sizing: inherit on descendants?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: box-sizing is not inherited by default.

    The html rule sets a root value, and the explicit inherit rule propagates it while allowing a component to choose content-box at its own root.

Percentage padding follows the containing inline size

Percentage padding and percentage margins use the containing block’s inline size, which is its width in horizontal writing, even for physical top and bottom padding. The frame below is 640 px wide and only 100 px tall:

Percentages use the containing block’s width?

Percentage padding in a 640px frame HTML · percent-padding.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Percentage padding and aspect-ratio</title>
  <style>
    body { margin: 0; }
    .frame { inline-size: 640px; block-size: 100px; }
    .half { padding-block-start: 50%; background: #dde; }
    .ratio-padding { block-size: 0; padding-block-start: 56.25%; background: #ded; }
    .ratio-modern { aspect-ratio: 16 / 9; background: #edd; }
  </style>
</head>
<body>
  <div class="frame">
    <div class="half" id="half"></div>
    <div class="ratio-padding" id="old"></div>
    <div class="ratio-modern" id="new"></div>
  </div>
  <script>
    const report = () => {
      const w = document.querySelector('.frame').offsetWidth;
      const h = (id) => document.getElementById(id).getBoundingClientRect().height;
      console.log(`frame ${w}px wide, 100px tall: 50% padding ${h('half')}px, 56.25% padding ${h('old')}px, aspect-ratio ${h('new')}px`);
    };
    report();
    document.querySelector('.frame').style.inlineSize = '360px';
    report();
  </script>
</body>
</html>
Frame 50 % padding 56.25 % padding 16 / 9 ratio
640 px wide 320 px 360 px 360 px
360 px wide 180 px 202.5 px 202.5 px

The fixture keeps the frame 100 px tall in both cases, yet the 50 % padding is half of 640, not half of 100. Before aspect-ratio existed, this rule was the standard way to build a box with a fixed ratio: an empty element with padding-top: 56.25% is always 16:9, because 56.25 % is 9 ÷ 16. The trick needs a height of 0 and absolutely positioned children, and its padding is unusable for anything else. aspect-ratio states a preferred ratio directly and leaves padding available for spacing; the sizing lesson in this module shows it with images.

Keep the frame height unchanged in this scene and switch its width from 640 to 360 px. Predict the top padding for 50 % and 56.25 % before each reveal:

Interactive · stage by stage A shorter frame does not change percentage padding Keep block-size at 100 px and predict padding as the frame changes from 640 to 360 px wide.
A shorter frame does not change percentage padding, step 4 of 4. Showing Containing inline size (360 px; height 100 px), Padding percentage (50%), Resolved padding (180 px). In focus: Resolved padding.Containing inline size360 px; height 100 pxPadding percentage50%Resolved padding180 px

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. Half of 640. The horizontal-writing frame is 640 px wide and 100 px tall. Top padding of 50% uses the 640 px inline size, giving 320 px.
  2. The 16:9 percentage. Change the padding percentage to 56.25%, which is 9 divided by 16. At 640 px the padding is 360 px; the frame height remains irrelevant to this basis.
  3. Narrow the same frame. At 360 px wide, the same 56.25% gives 202.5 px. The program computes 360 × 0.5625, keeping its input and this scene in agreement.
  4. Check the half again. At that 360 px inline size, 50% is 180 px. Changing the frame height alone would change neither of these padding calculations.

The 360 px frame produces 180 px and 202.5 px of padding. The card program prints the same 56.25 % calculation; changing the frame height alone cannot change that percentage basis.

Checkpoint

Check: The basis of percentage padding

  1. Question 1 of 2 A horizontal-writing containing block is 640 px wide and 100 px tall. How much top padding is 50%?

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 320 px

    The containing inline size is 640 px. Half of that is 320 px, even though the frame is only 100 px tall.

  2. Question 2 of 2 The same horizontal frame narrows to 360 px. What is padding-top: 56.25%?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 202.5 px

    Multiply the new inline size by 9/16: 360 × 0.5625 = 202.5 px. Keeping the height unchanged does not keep the percentage padding unchanged.

Inline padding can paint beyond its line without making room

A span, an a or an em in a paragraph generates an inline box, and inline boxes follow different rules in the vertical direction. Their padding and borders are painted, but the height of each line is still worked out from their line-height contribution and alignment with the other boxes on the line; that padding and border do not enlarge the contribution, and the top/bottom margins of this horizontal-writing non-replaced inline word have no effect on that line-height calculation. Three paragraphs with 24 px lines and a word on line 2 show it; in the last two the word gets 12 px of padding above and below, a border and 30 px margins:

Padding and borders on inline elements

Padding on a word in a paragraph HTML · inline-padding.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Padding on inline boxes</title>
  <style>
    body { margin: 0; }
    p { margin: 0 0 20px; font: 16px/24px Arial, sans-serif; }
    .tag { padding-block: 12px; border: 1px solid #555; background: #ffd; margin-block: 30px; }
    .tag.atomic { display: inline-block; }
  </style>
</head>
<body>
  <p id="plain">The first line of the paragraph,<br><span>a word</span> on the second line<br>and a third line.</p>
  <p id="padded">The first line of the paragraph,<br><span class="tag">a word</span> on the second line<br>and a third line.</p>
  <p id="inline-block">The first line of the paragraph,<br><span class="tag atomic">a word</span> on the second line<br>and a third line.</p>
  <script>
    // Each line box is 24px tall, so line 2 starts 24px below the paragraph's top and ends at 48px.
    const px = (n) => Math.round(n * 100) / 100; // engines measure in fractions of a pixel
    for (const id of ['plain', 'padded', 'inline-block']) {
      const p = document.getElementById(id);
      const box = p.querySelector('span').getBoundingClientRect();
      const top = px(box.top - p.getBoundingClientRect().top);
      console.log(`${id}: paragraph ${p.offsetHeight}px tall; the span paints from ${top}px to ${px(top + box.height)}px`);
    }
  </script>
</body>
</html>
The word Paragraph height Word box paints
plain 72 px 27 to 44 px
padded 72 px 14 to 57 px
padded, inline-block 158 px 54 to 104 px

Line 2 runs from 24 to 48 px. The padded word paints about 10 px into the line above and the line below while every line stays where it was, so its background covers part of the neighbouring text. The 30 px margins changed nothing. The painting coordinates are one worked set for the fixture’s font, not a portable font measurement. Different engines can choose different content-area font metrics; a two-pixel difference in the word box does not imply a change to these three 24 px line boxes. As an inline-block, the word becomes one solid box in the line: its padding, border and margins all take space, so line 2 grows to 30 + 50 + 30 = 110 px and the paragraph to 158 px.

Use plain inline padding for a light highlight that may overlap, and keep it small. When the box needs real room, such as a badge in a sentence or a link that should be easy to tap, make it inline-block or inline-flex. Inline-axis padding, borders and margins do take room. Those are physical left/right sides in this horizontal-writing paragraph, so they push the next word along its line.

Follow the same three-line paragraph. Separate the box that paints from the contribution that makes room on the line:

Interactive · step by step Paint can grow without giving the line more room Compare a plain word, a padded inline word and the same word as an atomic inline-block.
Paint can grow without giving the line more room, step 4 of 4. Showing Line contribution (still 24 px), Painted box (12 px padding per side), Three-line paragraph (24 + 110 + 24 = 158), Atomic margin box (110 px contribution). In focus: Atomic margin box, Three-line paragraph.Line contributionstill 24 pxPainted box12 px padding per sideThree-line paragraph24 + 110 + 24 = 158Atomic margin box110 px contribution

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. Three plain lines. Three 24 px lines give the fixture a 72 px paragraph. A non-replaced inline word contributes its line-height, not the height of its painted padding box.
  2. Add vertical padding. The word receives 12 px above and below plus a border. Its background and border extend into adjacent lines, but those additions do not increase its line-height contribution.
  3. Margins do not make room. The 30 px block-start and block-end margins do not enlarge a non-replaced inline line contribution either. Font metrics decide the exact painted top and bottom.
  4. Make the word atomic. As inline-block, the fixture contributes its full margin box: 30 + 50 + 30 = 110 px. Add the other two 24 px lines to get the worked paragraph height of 158 px.

The plain and padded inline cases keep a 72 px paragraph in this fixture. The atomic inline-block case contributes its 110 px margin box instead; the neighbouring 24 px lines bring the total to 158 px. A line containing other fonts, replaced elements or different vertical alignment needs its own line-box calculation.

Checkpoint

Check: Painted padding and line-box space

  1. Question 1 of 2 Only padding-block changes on a non-replaced inline word; its line-height and vertical alignment stay fixed. What does that padding change?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Its painted box, without adding padding to the line-height contribution.

    Distinguish ink from layout: the added padding can overlap another line while the line-height contribution stays fixed.

  2. Question 2 of 2 In the worked fixture, the atomic word contributes a 110 px margin box and the other two lines are 24 px each. What is the paragraph height?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 158 px

    The worked total is 24 + 110 + 24 = 158 px. That is this fixture’s calculation, not a font-independent claim for every inline-block.

Outlines and shadows do not add layout width

A keyboard user needs to see which control has focus, and the ring that shows it must not shift the page. Three common ways to draw it can be compared in turn on a button with a 1 px border, and its neighbour was measured: a border thickened to 3 px, a 3 px outline with a 2 px offset, and a 3 px spread shadow.

Focus rings that move nothing

Three focus rings, measured HTML · focus-ring.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Focus styles that move nothing</title>
  <style>
    body { margin: 16px; font: 16px/1.5 Arial, sans-serif; }
    button { font: inherit; padding: 8px 16px; border: 1px solid #555; border-radius: 8px; margin-inline-end: 8px; }
    /* Three ways to draw a focus ring; the script adds each class in turn. */
    .ring-border { border-width: 3px; }
    .ring-outline { outline: 3px solid #1a5fb4; outline-offset: 2px; }
    .ring-shadow { box-shadow: 0 0 0 3px #1a5fb4; }
  </style>
</head>
<body>
  <button id="first">Save</button><button id="next">Cancel</button>
  <script>
    const first = document.getElementById('first');
    const next = document.getElementById('next');
    const before = { width: first.offsetWidth, left: next.offsetLeft };
    for (const ring of ['ring-border', 'ring-outline', 'ring-shadow']) {
      first.classList.add(ring);
      console.log(`${ring}: Save grows by ${first.offsetWidth - before.width}px, Cancel moves by ${next.offsetLeft - before.left}px`);
      first.classList.remove(ring);
    }
  </script>
</body>
</html>
Ring Grows by Next button moves
3 px border 4 px 4 px
3 px outline 0 px 0 px
3 px shadow 0 px 0 px

A thicker border changes the border box, so everything after it moves on every focus change. An outline is drawn without taking layout space; outline-offset sets its distance from the edge. CSS UI says an outline following the border edge should follow its border-radius, while leaving the precise outline shape to the user agent. A box-shadow with a spread and no blur takes no space either, and also follows the radius.

The difference shows in forced colours mode, which the contrast themes of Windows turn on, where the browser replaces the page’s colours with the user’s palette when the element uses the default forced-color-adjust: auto. It then removes box-shadow, so a ring drawn only with a shadow disappears, while an outline’s colour is replaced with a system colour and stays visible, even when the outline was transparent:

Focus rings that work everywhere CSS · focus-rings.css
/* A ring for keyboard focus that takes no space: the outline is drawn outside the border and moves nothing. */
:focus-visible {
  outline: 3px solid #1a5fb4;
  outline-offset: 2px;
}

/* A ring drawn with box-shadow moves nothing either, but forced colours mode (the contrast themes of Windows) removes
   box-shadow with the default forced-color-adjust: auto. The transparent outline can receive a system colour,
   so a ring is still drawn without relying on the removed shadow. */
.chip:focus-visible {
  outline: 2px solid transparent;
  box-shadow: 0 0 0 3px #1a5fb4;
}

Use :focus-visible rather than :focus: it matches when the browser decides that focus should be shown, which includes keyboard focus but usually not a mouse click on a button. Never remove the outline without drawing something in its place. WCAG 2.2 requires a visible focus indicator at level AA (success criterion 2.4.7), and its level AAA criterion 2.4.13 asks for an indicator with at least the area of a 2 px thick perimeter around the control, whose pixels change with a contrast of at least 3:1 between the unfocused and the focused state.

Compare the border, outline and shadow on the same button. In the last step, consider what remains when the user agent forces colours:

Interactive · step by step A focus indicator must survive without moving neighbours Compare the same button with a thicker border, an outline and a shadow; finish with forced colours.
A focus indicator must survive without moving neighbours, step 5 of 5. Showing Button border box (original layout width), Next button (0 px shift), Focus indicator (system-colour outline), Forced-colours mode (shadow computes to none). In focus: Focus indicator, Forced-colours mode.Button border boxoriginal layout widthNext button0 px shiftFocus indicatorsystem-colour outlineForced-colours modeshadow computes to none

The drawing shows the whole scene; its 5 steps are listed below.

Every step as text
  1. Start with a 1 px border. The content-sized fixture button begins with a 1 px border on each side. Its next neighbour supplies a position to compare after a focus style changes.
  2. A border adds layout width. A 3 px border adds 2 px per side compared with the original border. The total width grows by 4 px, so the next button in this fixture moves by 4 px.
  3. An outline adds no room. A 3 px outline with a 2 px offset is drawn without taking layout space. The original border and neighbour position remain unchanged; clipping and contrast still matter.
  4. A shadow also takes no room. A 3 px spread shadow draws outside the button without adding layout width. That makes it stable, but a shadow alone is not a robust forced-colours focus indicator.
  5. Keep an outline fallback. With forced-color-adjust: auto, forced colours removes box shadows and supplies system colours for outlines. The transparent 2 px outline in focus-rings.css gives the shadow style a visible fallback.

A 3 px border adds 4 px across two sides of this content-sized button. An outline and a spread shadow add no layout width, but only the outline supplies the shadow-only style with a focus indicator after shadows are removed. Contrast and clipping still need attention.

Checkpoint

Check: Visible focus without layout movement

  1. Question 1 of 2 The content-sized button changes from a 1 px border to a 3 px border on each side. How much horizontal width is added?

    Type a number.

    Show the answer: Question 1 of 2

    Answer: 4 px

    Each border grows by 2 px. Across two sides the change is 4 px; an outline or shadow would add no layout width.

  2. Question 2 of 2 With forced-color-adjust: auto, a focus style uses a shadow and a transparent outline. Which part supplies its forced-colours fallback?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: The outline, whose colour is supplied from the user’s palette.

    The outline remains the focus indicator when shadows compute to none. Its thickness alone still does not prove the required contrast or freedom from clipping.

CSS Box Shadow Generator Build a spread-only shadow ring visually, then pair it with a transparent outline as above.

Logical sides follow writing mode and direction

Many current stylesheets, and the examples on this page, write margin-inline, padding-block or inline-size instead of margin-left, padding-top or width. These logical properties name the sides by the direction of the text: in horizontal English text, the logical axis: An axis defined by text flow: inline follows the text line and block follows block progression; its physical direction depends on writing mode. runs left to right and the block axis runs top to bottom, so padding-block: 12px sets the top and bottom padding. In a right-to-left language or vertical text they follow the text, which is why they are worth the habit. The international layout module of this track covers them in full.

Use the same card to distinguish a direction from an amount: padding-inline: 24px still assigns 24 px to each inline side, and padding-block: 12px assigns 12 px to each block side. Right-to-left text reverses inline-start and inline-end; a vertical writing mode changes which physical axis is inline. Step through those mappings:

Logical names: margin-inline and padding-block

Interactive · step by step The same padding values follow the writing axes Track 24 px on each inline side and 12 px on each block side as writing direction and mode change.
The same padding values follow the writing axes, step 4 of 4. Showing Inline sides (top and bottom: 24 px), Block sides (right and left: 12 px), Writing mode (vertical-rl; direction ltr), Text direction (rtl). In focus: Inline sides, Writing mode, Text direction.Inline sidestop and bottom: 24 pxBlock sidesright and left: 12 pxWriting modevertical-rl; direction ltrText directionrtl

The drawing shows the whole scene; its 4 steps are listed below.

Every step as text
  1. Horizontal English text. In horizontal left-to-right text, inline sides are left and right and block sides are top and bottom. Padding-inline: 24px and padding-block: 12px keep those amounts on each corresponding side.
  2. Reverse the text direction. With direction: rtl, inline-start becomes the right side and inline-end the left. Both still receive 24 px here because the shorthand assigns the same value to both sides.
  3. Use vertical writing. In vertical-rl with left-to-right inline progression, inline sides are top and bottom and block sides are right and left. The 24 px and 12 px amounts now map to those physical axes.
  4. Physical names stay physical. Padding-left keeps selecting the physical left side. Padding-inline-start selects the start of the inline axis, so its physical side depends on the writing mode and direction.

The numbers did not change when the names moved to other sides. A logical property describes the text flow, whereas a physical property such as padding-left keeps naming the physical left edge. Check the writing mode as well as direction before translating between them.

Checkpoint

Check: Logical sides follow the text flow

  1. Question 1 of 2 In horizontal left-to-right text, which sides receive padding-inline: 24px?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Left and right.

    Logical properties select sides by text flow; the horizontal left-to-right inline axis runs from left to right.

  2. Question 2 of 2 Use vertical-rl with direction: ltr, padding-inline: 24px and padding-block: 12px. What physical top padding is assigned?

    Type a number.

    Show the answer: Question 2 of 2

    Answer: 24 px

    The inline axis is vertical here, so its start and end are the physical top and bottom. The block-axis amount applies to right and left instead.

Practise: hit an exact size

Designs give sizes as they appear on screen. Before writing CSS for them, it helps to work out what to type.

Exercise · Easy · JavaScript

Work out the width to write for an exact card size

A design gives the size of every card as it appears on screen: its border box. Before you write the CSS, work out the numbers. Write two functions in sizes.mjs and export them. Each takes one object; padding and border are the widths on each side, in px, and boxSizing is 'content-box' or 'border-box' (when it is missing, the default 'content-box' applies). The same sums work for widths and for heights.

The first function, renderedSize({ size, padding, border, boxSizing }), returns the size of the border box a browser draws for width: <size>px (or height). Under border-box the content box can't be smaller than 0, so when the padding and border need more room than size, they win: renderedSize({ size: 40, padding: 24, border: 1, boxSizing: 'border-box' }) is 50.

The second, sizeToWrite({ target, padding, border, boxSizing }), returns the number to write in width (or height) so that the border box is exactly target px. For a 320 px card with 24 px of padding and a 1 px border that is 270 under content-box and 320 under border-box. When no value can give that size, because the padding and borders of the two sides alone are wider than target, throw a RangeError.

The sample tests import both functions from sizes.mjs and run in your browser.

Starter code · sizes.mjs

/** The border-box size (px) a browser draws for `width: <size>px` with this padding and border on each side. */
export function renderedSize({ size, padding, border, boxSizing = 'content-box' }) {
  // Replace this line with your code.
  return size;
}

/** The value (px) to write in width or height so that the border box is exactly `target` px. */
export function sizeToWrite({ target, padding, border, boxSizing = 'content-box' }) {
  // Replace this line with your code.
  return target;
}
The sample tests · sizes.test.mjs
import { test, assert } from 'mysmartcopilot:test';
import { renderedSize, sizeToWrite } from './sizes.mjs';

const card = { padding: 24, border: 1 };

test('content-box adds the padding and the border of both sides', () => {
  assert.equal(renderedSize({ size: 300, ...card, boxSizing: 'content-box' }), 350);
  assert.equal(renderedSize({ size: 200, padding: 10, border: 2, boxSizing: 'content-box' }), 224);
});

test('content-box is the default when boxSizing is missing', () => {
  assert.equal(renderedSize({ size: 300, ...card }), 350);
  assert.equal(sizeToWrite({ target: 320, ...card }), 270);
});

test('border-box draws the size you write', () => {
  assert.equal(renderedSize({ size: 300, ...card, boxSizing: 'border-box' }), 300);
  assert.equal(renderedSize({ size: 51, ...card, boxSizing: 'border-box' }), 51);
});

test('under border-box, padding and border win when they need more room', () => {
  assert.equal(renderedSize({ size: 40, ...card, boxSizing: 'border-box' }), 50);
  assert.equal(renderedSize({ size: 0, padding: 8, border: 0.5, boxSizing: 'border-box' }), 17);
});

test('the width to write for a 320 by 200 px card', () => {
  assert.equal(sizeToWrite({ target: 320, ...card, boxSizing: 'content-box' }), 270);
  assert.equal(sizeToWrite({ target: 200, ...card, boxSizing: 'content-box' }), 150);
  assert.equal(sizeToWrite({ target: 320, ...card, boxSizing: 'border-box' }), 320);
});

test('a target exactly as wide as padding plus border leaves no room for content', () => {
  assert.equal(sizeToWrite({ target: 50, ...card, boxSizing: 'content-box' }), 0);
  assert.equal(sizeToWrite({ target: 50, ...card, boxSizing: 'border-box' }), 50);
});

test('a target smaller than padding plus border throws a RangeError', () => {
  assert.throws(() => sizeToWrite({ target: 49, ...card, boxSizing: 'content-box' }), RangeError);
  assert.throws(() => sizeToWrite({ target: 49, ...card, boxSizing: 'border-box' }), RangeError);
});

test('what you write is what renders, in both models', () => {
  for (const boxSizing of ['content-box', 'border-box']) {
    for (const target of [50, 64, 199.5, 320, 1000]) {
      const size = sizeToWrite({ target, ...card, boxSizing });
      assert.equal(renderedSize({ size, ...card, boxSizing }), target, `${boxSizing}, ${target}px`);
    }
  }
});
A hint

Both functions need the room that padding and border take on the two sides together: 2 * (padding + border). Under content-box, renderedSize adds that room to size and sizeToWrite subtracts it from target. Under border-box, the size you write is the border box, unless the room alone is larger: then the box is that room.

The sample tests run on this device, in your browser (QuickJS): nothing is sent to mysmartcopilot.com. The first run downloads JavaScript (about 0.6 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

Use the adaptive questions to revisit the edge, percentage and focus decisions. Each answer explains the calculation or the misconception:

Practice that adapts to you

Practise this lesson

14 questions about 6 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 14 A card has width: 280px; padding: 20px; border: 2px solid and the default box-sizing. How wide is its border box, the width offsetWidth reports?

    Type a number.

    Show the answer: Question 1 of 14

    Answer: 324 px

    Under content-box the width you write is the content width, and the padding and border of both sides are added outside it: 280 + 2 × 20 + 2 × 2 = 324 px. With box-sizing: border-box the same card would be 280 px wide, and its content 236 px.

  2. Question 2 of 14 Which declaration makes width and height include the padding and the border?

    Choose one answer.

    Show the answer: Question 2 of 14

    Answer: box-sizing: border-box

    box-sizing: border-box applies the sizing properties to the border box, so padding and border are drawn inside the size you write. content-box is the default and applies them to the content box. background-clip only decides where the background is painted, and outlines never take space at all.

  3. Question 3 of 14 An element sits in a containing block 480px wide and 900px tall and has padding-top: 25%. How tall is that padding?

    Type a number.

    Show the answer: Question 3 of 14

    Answer: 120 px

    Percentages in padding and margin resolve against the inline size of the containing block, its width in horizontal writing, even for the top and bottom sides: 25 % of 480 px is 120 px. The 900 px height plays no part, which is what made the old trick of a fixed-ratio box made with padding work.

  4. Question 4 of 14 A span inside a paragraph gets padding-block: 12px and a background. What happens to the lines of the paragraph?

    Choose one answer.

    Show the answer: Question 4 of 14

    Answer: The background grows up and down over the lines next to it, and the lines stay where they were.

    On a non-replaced inline box, vertical padding and borders are painted but the line boxes are still sized from line-height contributions and vertical alignment; the added padding can overlap neighbouring lines. In the worked fixture the padded span painted about 10 px into the lines above and below while its three 24 px line boxes give a 72 px paragraph. Use inline-block when the padding should make room.

  5. Question 5 of 14 A button has a 1 px border. Which focus style moves the button next to it?

    Choose one answer.

    Show the answer: Question 5 of 14

    Answer: Changing the border to 3 px on focus

    A thicker border makes the border box grow, here by 2 px on each side, so the next button in this content-sized fixture moves 4 px. Outlines and shadows are painted without taking space, and a background colour changes no size.

  6. Question 6 of 14 With this CSS, which box-sizing does a paragraph inside .legacy-widget use?

    Read the code, then choose one answer.

    html { box-sizing: border-box; }
    *, *::before, *::after { box-sizing: inherit; }
    .legacy-widget { box-sizing: content-box; }
    Show the answer: Question 6 of 14

    Answer: content-box, inherited from .legacy-widget

    The universal rule sets every element to inherit, so each takes its parent's value. The widget switches its own box back to content-box, and everything inside follows. box-sizing is not inherited on its own: the inherit keyword in the second rule is what passes it down.

  7. Question 7 of 14 For the 300 px card with 24 px padding and 1 px borders, which size includes the border but excludes margin?

    Choose one answer.

    Show the answer: Question 7 of 14

    Answer: 350 px.

    Identify the edge before choosing the number: content, padding, border and margin widths describe different areas.

  8. Question 8 of 14 A card’s border box is 350 px wide, with 16 px margins on each side. What is its outer margin-box width?

    Type a number.

    Show the answer: Question 8 of 14

    Answer: 382 px

    Its margins add 32 px outside the border, so the outer footprint is 350 + 32 = 382 px.

  9. Question 9 of 14 A horizontal-writing frame stays 640 px wide but its height changes from 100 to 200 px. What happens to its child’s padding-top: 50%?

    Choose one answer.

    Show the answer: Question 9 of 14

    Answer: It stays 320 px.

    The percentage basis and the side being padded are different questions; a top side can still use the containing inline size.

  10. Question 10 of 14 Keep the worked atomic word at 110 px of margin-box contribution but make the other two lines 20 px each. What total does this line-box model predict?

    Type a number.

    Show the answer: Question 10 of 14

    Answer: 150 px

    Add the three contributions in the stated fixture: 20 + 110 + 20 = 150 px. This question supplies the atomic contribution rather than asking you to guess font metrics.

  11. Question 11 of 14 A chip’s focus ring is drawn with box-shadow. Which addition keeps a layout-stable fallback for forced-colours mode?

    Choose one answer.

    Show the answer: Question 11 of 14

    Answer: A 2 px transparent outline on :focus-visible.

    Use a real outline as the fallback. Contrast, area and clipping still determine whether the actual visible indicator satisfies the accessibility requirements.

  12. Question 12 of 14 In horizontal text, padding-block: 12px supplies which pair of physical sides?

    Choose one answer.

    Show the answer: Question 12 of 14

    Answer: Top and bottom.

    The block axis follows the direction in which blocks stack; it is vertical in horizontal writing.

  13. Question 13 of 14 Keep horizontal writing and set direction: rtl. Where does padding-inline-start: 24px put its padding?

    Choose one answer.

    Show the answer: Question 13 of 14

    Answer: On the physical right.

    Both the writing mode and direction determine a flow-relative side. A physical padding-left declaration would keep selecting left instead.

  14. Question 14 of 14 The containing inline size halves from 640 to 320 px while padding-top stays 56.25%. Which result follows?

    Choose one answer.

    Show the answer: Question 14 of 14

    Answer: Padding halves from 360 to 180 px.

    The program’s formula is inline size multiplied by 0.5625. Halving that size halves the computed padding.

Interview questions

Fresher · What is the difference between box-sizing: content-box and border-box, and why do many projects set border-box everywhere?

With content-box, the default, width and height set the content area, and padding and border are added outside it, so a 300 px wide box with 24 px of padding and a 1 px border is drawn 350 px wide. With border-box, width and height set the border box: the padding and border are drawn inside, and the content gets what is left, 250 px in the same example, never less than zero. Projects switch to border-box because designs give the size you see, padding can change without breaking a layout, and width: 100% plus padding no longer overflows its container. The usual setup puts box-sizing: border-box on html and inherit on every element, so a component that needs content-box can switch back in one place.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Fresher to mid

    A design shows three cards in a 1,000 px row with 20 px gaps, each 320 px wide with 24 px of padding and a 1 px border. With width: 320px on each card, the third card wraps to a new line. Explain the numbers, fix it, and keep it right when the padding changes.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Mid to senior

    A design system draws its focus rings with box-shadow, because outlines once ignored border-radius. An accessibility audit now reports that keyboard focus is invisible in Windows contrast themes. Explain why, and design a focus style that works everywhere without moving the layout.

    Model answer, Pro. First step and follow-ups

Key takeaways

  • Every box has four areas: content, padding, border and margin. Margins are transparent and may be negative; padding may not.
  • content-box (the default) adds padding and border outside width; border-box draws them inside it, and the content box never goes below zero.
  • Put box-sizing: border-box on html and box-sizing: inherit on every element and pseudo-element.
  • Percentage padding and margins use the containing block’s inline size: its width in horizontal writing, including for top/bottom padding. Use aspect-ratio for boxes with a fixed ratio.
  • Vertical padding and borders on inline boxes paint over the neighbouring lines without moving them; use inline-block when they need room.
  • Draw focus rings with outline and outline-offset on :focus-visible; if you use a box-shadow, add a transparent outline so forced colours mode still shows a ring.

Terms in this lesson

border box
The box enclosed by the border’s outer edges, including content and padding but excluding the surrounding margin.
content box
The inner box containing an element’s text, child boxes or replaced content, before surrounding padding, border and margin.
logical axis
An axis defined by text flow: inline follows the text line and block follows block progression; its physical direction depends on writing mode.

Corrections

  • Clarified box measurements, inline painting and focus requirements; the worked fixtures keep their original inputs.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.