Boxes and positioning
The box model
Visualize every element as content surrounded by padding, border, and margin, and see how those layers determine occupied space.
8 minute lesson
Layout works with boxes generated by elements and text. One element can generate more than one box, as inline content wraps across lines, but the block box model is the useful starting point.
From inside to outside, a box has:
- content
- padding
- border
- margin
.card {
width: 20rem;
padding: 1rem;
border: 2px solid;
margin: 1rem;
}
With the default content-box, width: 20rem sizes only the content. Horizontal padding and borders are added to produce the border box. Margins sit outside that border box and influence spacing, but are not painted by the element’s background.
Do not assume height includes all visible content. Text wrapping, replaced elements, minimum content sizes, and overflow can make the used result more complicated than the declaration.
Open DevTools and inspect the box-model diagram. It shows the calculated size of each layer and is often the fastest way to understand why a box is larger or farther away than expected.
Change padding, border, and margin one at a time. Predict the border-box width before reading the diagram. Then add a long unbreakable word and watch how content constraints can override your mental arithmetic.
Lesson completed