CSS Tutorial · CSS Basics · Lesson 6 of 19
CSS Box Model
Content, padding, border and margin — and box-sizing: border-box.
Every element is a box
From the inside out:
- Content — text or images, sized by
widthandheight. - Padding — space inside the border.
- Border.
- Margin — space outside, between this box and others.
<style>
.box {
width: 200px;
padding: 20px;
border: 6px solid #2563eb;
margin: 24px;
background: #dbeafe;
font-family: system-ui, sans-serif;
}
</style>
<div class="box">Content area with padding, border and margin.</div>
Shorthand values go clockwise from the top: margin: 10px 20px 10px 20px (top, right, bottom, left), or margin: 10px 20px (vertical, horizontal). margin: 0 auto centres a block with a width.
box-sizing
By default, width sets only the content width — padding and border are added on top, which makes sizing confusing. Almost every site sets:
*, *::before, *::after { box-sizing: border-box; }
Now width includes padding and border:
<style>
div { width: 200px; padding: 20px; border: 5px solid #7c3aed; margin-bottom: 10px; font: 13px system-ui; }
.content-box { box-sizing: content-box; }
.border-box { box-sizing: border-box; }
</style>
<div class="content-box">content-box: 250px wide in total</div>
<div class="border-box">border-box: exactly 200px wide</div>
Use your browser's DevTools (Inspect → Computed) to see the box model of any element.
Test yourself
Which property makes width include padding and border?
box-sizing: content-boxbox-sizing: border-boxwidth: totaldisplay: block
Show answer
Answer: box-sizing: border-box