CSS Child / The Box

Everything is a box, and every box has four rings.

Content, padding, border and margin are separate layers, and confusing them is the most common source of unexpected space.

Every visible thing on a page occupies a rectangular region, and that region is built from four nested rings that people frequently blur together. At the centre is the content: the text, the picture, whatever the thing actually is. Around that is padding, which is space held inside the boundary, so it takes the background colour and is part of the visible object. Around that is the border, the drawn edge itself, which may be invisible but still takes up room when present. Around all of it is the margin, which is space held outside the boundary, transparent, belonging to no one, keeping the object away from its neighbours.

The distinction between the inner space and the outer space is the one to get right, and it is worth a full minute of thought rather than a glance. Inner space makes the object itself larger and more generous: a button with generous inner space is a bigger, more comfortable button. Outer space does not change the object at all, it only pushes other things away from it: a button with generous outer space is exactly the same button with more room around it. When something looks cramped, deciding which of those two you actually mean will get you to the right answer immediately.

When you are learning, and something is spaced wrongly, the temptation is to try one, then the other, until the picture looks right. That works often enough to feel like a method and it is not one, because you have not learned anything and the next problem will be identical. Instead, before you type, say out loud what you want: more room inside this thing, or more distance between this thing and that one. The answer to that sentence tells you which ring to reach for, and after a few dozen repetitions you will stop needing to say it.