The CSS Box Model: Content, Padding, Border, Margin
To the browser, every element is a rectangle. Headings, paragraphs, images and even inline words are laid out as boxes, and each box has four layers, from the inside out:
- Content: the text or image itself, sized by
widthandheight. - Padding: space between the content and the border. It shows the element's background.
- Border: a line around the padding, set with
border: 2px solid #0e7490. - Margin: transparent space outside the border that pushes neighbors away.
Shorthand values
padding, margin and border-width accept one to four values, going clockwise from the top: padding: 8px 16px means 8px top and bottom, 16px left and right; margin: 0 auto 1rem means top 0, sides auto, bottom 1rem. margin: 0 auto on a block with a fixed width is the classic way to center it horizontally.
The width surprise
By default (box-sizing: content-box), width sets only the content width. Padding and border are added on top. A box with width: 200px, padding: 20px and a 5px border therefore takes up 250 pixels across. That arithmetic breaks layouts constantly.
box-sizing: border-box changes the meaning of width to include padding and border. The same box is then exactly 200 pixels wide, and its content area shrinks to fit. Most modern stylesheets switch every element to this model with one rule:
*, *::before, *::after { box-sizing: border-box; }
The example draws two boxes with identical width, padding and border and prints the rendered width of each, measured with getBoundingClientRect().
Expected page text
content-box border-box content-box on screen: 250px border-box on screen: 200px
Margin collapsing
When the bottom margin of one block touches the top margin of the next, they do not add up. The larger of the two is used. So a paragraph with margin-bottom: 24px followed by one with margin-top: 16px ends up 24 pixels apart, not 40. This only happens to vertical margins of block boxes in normal flow; it does not happen inside Flexbox or Grid containers, and padding never collapses.
Inspecting boxes
Every browser's developer tools show a box-model diagram for the selected element with the four layers labeled and measured. When spacing looks wrong, inspect the element and check whether the gap is padding, border or margin, and on which element.
Summary
- Content, padding, border and margin stack from the inside out.
- With
content-box,widthexcludes padding and border;border-boxincludes them. - Adjacent vertical margins collapse to the larger value.
Quiz: Box model