The box model
In CSS, every element is a rectangular box. The box has four layers, from the inside out:
Diagram
┌──────────────── margin ────────────────┐
│ ┌────────────── border ──────────────┐ │
│ │ ┌──────────── padding ───────────┐ │ │
│ │ │ content │ │ │
│ │ └────────────────────────────────┘ │ │
│ └────────────────────────────────────┘ │
└────────────────────────────────────────┘- content: the text or image
- padding: space inside the border, around the content
- border: the line around the padding
- margin: space outside the border, pushing other elements away
HTML
<style>
.box {
width: 220px;
padding: 20px;
border: 4px solid #5a48f5;
margin: 24px;
background: #eef0ff;
font-family: system-ui;
}
</style>
<div class="box">Content with padding, a border and a margin.</div>
<div class="box">A second box, 24px away.</div>Shorthand
padding and margin accept one to four values, going clockwise from the top:
CSS
padding: 10px; /* all four sides */
padding: 10px 20px; /* top & bottom, left & right */
padding: 10px 20px 30px 40px; /* top, right, bottom, left */
margin: 0 auto; /* centre a block with a set width */How wide is the box?
By default, width sets only the content width. Padding and border are added on top:
HTML
<style>
.a, .b { width: 200px; padding: 20px; border: 5px solid #0aa9cf; margin-bottom: 10px; font-family: system-ui; }
.b { box-sizing: border-box; }
</style>
<div class="a">content-box: really 250px wide</div>
<div class="b">border-box: really 200px wide</div>200 + 20 + 20 + 5 + 5 = 250px. That arithmetic is annoying, so almost every modern site switches to border-box, where width includes padding and border:
CSS
*, *::before, *::after {
box-sizing: border-box;
}Margin collapse
When two vertical margins meet, they collapse into the larger of the two instead of adding up:
HTML
<style>
.p1 { margin-bottom: 30px; background: #fff4dc; }
.p2 { margin-top: 20px; background: #e6f9ff; }
</style>
<p class="p1">margin-bottom: 30px</p>
<p class="p2">margin-top: 20px. The gap is 30px, not 50px.</p>Finished this lesson?Mark it complete to earn +20 XP and move your progress on.