Here is the single most important concept in CSS layout: every element is a rectangular box. Once you understand its four layers, all spacing and sizing finally make sense.
The four layers
From the inside out: content (the text or image), padding (space inside, around the content), border (a line around the padding), and margin (space outside, pushing other elements away).
<div class="box">Box model</div>.box{background:#dbeafe;padding:20px;border:3px solid #2563eb;margin:24px}Padding vs margin
- Inside the box
- Within background & border
- Inner breathing room
- Outside the box
- Always transparent
- Space between boxes
box-sizing: the fix everyone uses
By default, width does not include padding and border, so a 200px box with 20px padding is actually 240px wide. <code>box-sizing: border-box</code> fixes this so width includes padding and border. Almost every project applies it to everything.
<div class="card">Exactly 200px wide</div>*{box-sizing:border-box}
.card{width:200px;padding:20px;border:2px solid #2563eb;background:#eff6ff}.card { width: 200px; padding: 20px; }
/* actually 240px wide */* { box-sizing: border-box; }
.card { width: 200px; padding: 20px; }
/* stays 200px */Without border-box, adding padding makes elements wider than you set, breaking layouts.
Start every stylesheet with * { box-sizing: border-box; }. It makes sizing intuitive and is one of the most universal habits in modern CSS.
Build two boxes with border-box. Give them padding, a border and a background, and use margin to space them apart. Confirm changing padding does not change total width.
1. The four layers, inside out?
2. Which is space INSIDE the box?
3. box-sizing: border-box makes width…
- Every element is a box: content, padding, border, margin.
- Padding is inside; margin is the space outside.
- box-sizing: border-box makes width include padding and border.
- Apply border-box to everything for predictable sizing.