Recess
Sign in
← Back to feed
You're reading as a guest. Sign in to save posts, see what's new, and tune your feed.
Sign in
WEB DEVELOPMENT · BITE · 2 MIN · BEGINNER

CSS box model in 2 minutes

Every web element is a rectangle inside three other rectangles. Most of CSS is knowing which one you're sizing.

Open the devtools on any website, click an element, and look at the colored diagram in the inspector: a blue inner box, a green ring around it, a yellow ring around that, and an orange ring around the outside. That is the CSS box model, and it has been the basis of web layout since CSS1 in 1996.

The four rings, from inside out: content (the actual text or image), padding (transparent space inside the border), border (the visible edge), and margin (transparent space outside the border, pushing other elements away). When you write width: 200px, you are by default setting the content width. Add padding: 20px and border: 2px solid and the element actually occupies 244 pixels on screen — content plus padding-left plus padding-right plus border-left plus border-right. This is the source of approximately one billion frustrated CSS bugs since 1996.

The fix is one line: box-sizing: border-box. With that set, width: 200px means the border box is 200 pixels — padding and border now eat into the content area instead of adding to the outside. The element is exactly as wide as you said. Almost every modern site sets * { box-sizing: border-box; } once at the top of the stylesheet and forgets the original behavior exists. Bootstrap did this in 2013, Tailwind does it in its preflight, and the W3C added the property to the spec specifically because the default was a footgun.

Margins still live outside the border box and still collapse vertically (two stacked elements with margin: 20px end up 20 pixels apart, not 40). That quirk is older than CSS and isn't going anywhere. Set border-box, learn margin collapse, and the rest of layout gets noticeably less mysterious.

#css#web#box-model#frontend#layout
Sources
MDN Web DocsMDN Web DocsW3C