CSS Child / The Box

Why width does not always mean what you expect it to.

The oldest surprise in styling is that stating a size may describe only part of the box.

Here is the classic shock. You give something a width. You then add inner space and a visible edge. You measure the result and it is wider than the number you stated. Nothing has malfunctioned. By the original design of the system, the size you state describes the content region alone, and the inner space and the edge are added on the outside of that measurement. So the total occupied width is your number plus both sides of the inner space plus both sides of the edge. Two things you thought were separate decisions turn out to be joined, and a row of items that should fit exactly now overflows.

The rescue is a setting that changes the meaning of the measurement, so that the number you state describes the whole box up to and including the edge, with the inner space and the edge taken out of the inside rather than added to the outside. State a size and it stays that size, no matter how much inner space you add later. Nearly everyone who works with this system turns this behaviour on for everything, once, at the very top of their styling, and never thinks about it again, and this is genuinely the standard advice rather than a clever trick.

Understand why it exists rather than just copying the habit. The point is that there are two reasonable definitions of how big something is, one measuring the space for its contents and one measuring the footprint it occupies, and the system originally chose the first while almost every layout task wants the second. Knowing that both definitions are coherent means you will not be baffled when you meet the original behaviour in something you did not write, and you will be able to explain to yourself, in one sentence, exactly what is happening.