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.
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
What you’ll learn
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
On this page
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
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.
- 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.
- Inside it is the border box: 350 px wide, with 1 px of border on each side. This is the width offsetWidth reports.
- 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.
- 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,
widthandheightset 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:
The drawing shows the whole scene; its 4 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- 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
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
<!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:
The drawing shows the whole scene; its 5 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- 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.
- 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 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
Runs on this device, in your browser. The first run downloads JavaScript (about 0.6 MB), which is kept for the next runs.
Your run, in this browser
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.
Border-box for a whole project
/* 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
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?
<!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:
The drawing shows the whole scene; its 4 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- 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
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
<!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:
The drawing shows the whole scene; its 4 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- 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
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
<!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:
/* 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:
The drawing shows the whole scene; its 5 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- 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.
- 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
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
The drawing shows the whole scene; its 4 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- 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
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.
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
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.
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.
-
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.
-
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.
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 outsidewidth;border-boxdraws them inside it, and the content box never goes below zero.- Put
box-sizing: border-boxonhtmlandbox-sizing: inheriton 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-ratiofor boxes with a fixed ratio. - Vertical padding and borders on inline boxes paint over the neighbouring lines without moving them; use
inline-blockwhen they need room. - Draw focus rings with
outlineandoutline-offseton:focus-visible; if you use abox-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
- CSS Box Model Module Level 4 (W3C CSS Working Group)
- CSS Box Sizing Module Level 3: the box-sizing property (W3C CSS Working Group)
- CSS 2: visual formatting model details (inline, non-replaced elements) (W3C CSS Working Group)
- CSS Basic User Interface Module Level 4: outline properties (W3C CSS Working Group)
- CSS Color Adjustment Module Level 1: properties affected by forced colors mode (W3C CSS Working Group)
- CSS Backgrounds and Borders Module Level 3: drop shadows (W3C CSS Working Group)
- CSS Box Sizing Module Level 4: aspect-ratio (W3C CSS Working Group)
- Selectors Level 4: the :focus-visible pseudo-class (W3C CSS Working Group)
- CSSOM View Module: offsetWidth and clientWidth (W3C CSS Working Group)
- Web Content Accessibility Guidelines (WCAG) 2.2: Focus Visible and Focus Appearance (W3C)
- Introduction to the CSS box model (MDN Web Docs) (Mozilla)
- Examine and edit the box model (Firefox DevTools) (Mozilla)
- Elements tab (Web Inspector Reference) (WebKit)
- CSS features reference (Chrome DevTools) (Google)
- CSS Logical Properties: flow-relative box model properties (W3C CSS Working Group)
- CSS Writing Modes: block and inline flow directions (W3C CSS Working Group)
- Emulate CSS media features in Chrome DevTools (Google)
- Playwright page.emulateMedia: forcedColors option (Microsoft Playwright)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress