The four layers
Every element is a rectangle built from the same four layers, content in the middle, then padding, then border, then margin on the outside.
Order from the center out: content, then padding, then border, then margin.
.card {
width: 300px; /* content width (by default) */
padding: 16px; /* inside space */
border: 1px solid #ddd; /* edge */
margin: 20px auto; /* outside space, auto centers block */
}
The one line that saves you: box-sizing: border-box
content-box (default)
Width here is content only. Padding and border get added on top, so boxes overflow their expected size.
border-box (recommended)
Width now includes padding and border. What you set is what you get.
/* put this FIRST in every stylesheet */
* { box-sizing: border-box; }
/* now width: 300px means total 300px, not 300 + padding + border */
This is why shared.css:1 starts with * { box-sizing: border-box; }. Copy that rule into every project.
width / height, max-width, and margin auto
max-width: 400px; margin: 0 auto;Caps at 400px but shrinks on small screens, and centers because it's a block with auto margins.
width:140px
margin:0 auto/* classic centered container */
.container {
max-width: 720px; /* don't get wider than this */
margin: 0 auto; /* center horizontally (block needs width/max-width) */
padding: 0 16px; /* breathing room on mobile */
}
margin: 0 auto only centers block elements with a set width or max-width. On inline elements or width:auto it does nothing. For flex or grid children, margin: auto centers on that axis too (see Module 9).Collapsing margins: the surprise
Vertical margins between blocks collapse instead of adding together. They overlap rather than stack.
margin: 20px 0margin: 20px 0The gap between A and B is 20px, not 40px, because the margins collapsed.
/* gap is 20px, not 40px */
h2 { margin-bottom: 20px; }
p { margin-top: 20px; } /* collapses with h2's bottom margin */
To avoid it: add padding or border to the parent, use gap with flex or grid, or just account for it when spacing things out.
Live demo: a button three ways
Same visual button, three different box model choices.
/* brittle, breaks if text wraps or font changes */
.btn-fixed { height: 36px; }
/* flexible, preferred */
.btn { padding: 10px 16px; border: 1px solid #111; }
/* fun variant */
.btn-pill { border-radius: 999px; }
height clips wrapped text and needs manual vertical centering. padding grows with the content and centers naturally.- Create three
<button>or<a>elements. - Style one with
height, one withpadding, one withborder-radius: 999px. - Inspect each in DevTools' Box Model panel and compare total sizes.
- Add
* { box-sizing: border-box; }and watch the numbers change.