The Box Model
Every element is a box
From the inside out:
- Content: the text or image.
- Padding: space inside the border.
- Border: the line around it.
- Margin: space outside, separating it from other elements.
.card {
width: 300px;
padding: 16px;
border: 1px solid #ddd;
margin: 20px auto; /* auto left/right centres a block */
}
box-sizing: the most useful reset
By default, width sets only the content, so padding and border make the box bigger than you asked. Fix it everywhere:
*, *::before, *::after { box-sizing: border-box; }
Now width: 300px means 300 px including padding and border.
Shorthand order
margin: 10px 20px 30px 40px; goes top, right, bottom, left (clockwise). margin: 10px 20px; means vertical then horizontal.
Margin collapsing
Vertical margins between blocks merge: a 20 px bottom margin above a 30 px top margin gives a 30 px gap, not 50. This doesn't happen in flex or grid layouts.
Seeing it
DevTools → Elements → Computed shows the box model diagram for any element.
Example
<style>
*, *::before, *::after { box-sizing: border-box; }
.card {
width: 260px;
padding: 16px;
margin: 20px auto;
border: 2px solid #6366f1;
border-radius: 12px;
background: #eef2ff;
font-family: sans-serif;
}
</style>
<div class="card">
<strong>260px wide</strong><br />
including padding and border, thanks to border-box.
</div>