Emmanuel Akinfulubi

HTML and CSSHTML and CSS

box-sizing: border-box explained in CSS

18 What width actually means

fair

Two boxes, same declared width, same padding and border, different box-sizing. Work out the rendered width of each from the numbers in the stylesheet.

Stuck? Three hints, smallest first
  1. 1. The default is content-box: width sizes the content only, and padding and border are added on.
  2. 2. border-box makes width the total, so padding and border eat into it.
  3. 3. Add it up: 200 content, 16 padding each side, 2 border each side.

index.html

<div class="box content">width: 200px, content-box</div>
<div class="box border">width: 200px, border-box</div>

style.css

.box {
  width: 200px;
  padding: 16px;
  border: 2px solid #3055d8;
  margin-bottom: 10px;
  background: #eef1fd;
  color: #17171a;
  font-size: 0.85rem;
}

.content {
  box-sizing: content-box;   /* the default: 200 + 32 + 4 = 236px on screen */
}

.border {
  box-sizing: border-box;    /* 200px on screen, 164px of it for content */
}
Rendered result. Shown, not machine-checked: there is no browser in the build.
7 checks that prove this answer

Assertions, run in the browser. The markup and styles above are handed to them as html and css, so press Run and each check prints ok. The build fails if a single one fails.

Checks for exercise 18

// Read the numbers out of the stylesheet, then do the arithmetic the browser does.
const declared = Number(/\swidth:\s*(\d+)px/.exec(css)[1]);
const pad = Number(/padding:\s*(\d+)px/.exec(css)[1]);
const border = Number(/border:\s*(\d+)px/.exec(css)[1]);

const contentBoxTotal = declared + pad * 2 + border * 2;
const borderBoxTotal = declared;
const borderBoxContent = declared - pad * 2 - border * 2;

test('the stylesheet declares 200px', declared, 200);
test('content-box renders 236px wide', contentBoxTotal, 236);
test('border-box renders exactly the 200px asked for', borderBoxTotal, 200);
test('and leaves 164px for the content', borderBoxContent, 164);
test('the two differ by the padding and border', contentBoxTotal - borderBoxTotal, pad * 2 + border * 2);
test('both models appear in the stylesheet', /content-box/.test(css) && /border-box/.test(css), true);
test('this is arithmetic on the source, not a measured box', typeof contentBoxTotal, 'number');

Output


      

Nothing here measures anything — there is no browser in the build, so the numbers come from adding up what the stylesheet says, which is exactly what the browser does. That is the point worth internalising: under the default content-box, width: 200px is a promise about the content only, so a box you asked to be 200 wide arrives at 236 and your two-column layout overflows. Most projects set box-sizing: border-box on everything once, at the top, and never think about it again.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.