The Box Model
The single most important concept in CSS. Every element is a box with content, padding, border and margin.
What you will learn
- Name the four layers of the box model
- Tell padding and margin apart
- Use the browser dev tools to inspect boxes
Every element is a box
CSS treats every element as a rectangular box with four layers, from inside out:
- Content — the text or image itself.
- Padding — space inside, between content and border.
- Border — a line around the padding.
- Margin — space outside, pushing other elements away.
<style>
.box {
width: 220px;
padding: 20px; /* space inside */
border: 4px solid #4338ca; /* the border */
margin: 24px; /* space outside */
background: #e0e7ff;
}
</style>
<div class="box">Content sits inside padding, inside the border. Margin is the gap outside.</div>
<div class="box">A second box — see the margin gap between us.</div>Look at one box and trace the four layers in the code from inside out:
- The text is the content — the innermost layer.
padding: 20pxadds 20px of space inside the box, between the text and the border (notice the text is not jammed against the edge).border: 4px solid #4338cadraws the indigo line around that padding.margin: 24pxadds 24px of space outside the border. That is the gap you see between the two boxes — their margins create the breathing room.
Note: Output: Two light-blue boxes, each with text padded away from a thick indigo border, and a clear gap between the two boxes. The gap is the margin; the inner space is the padding.
Tip: Open your browser dev tools (press F12), click an element, and look at the coloured box-model diagram. It is the fastest way to understand and debug spacing.
Note: Remember the difference: padding is space inside the box (pushes the content inward); margin is space outside (pushes neighbours away).
Q. Which layer is the space OUTSIDE the border, pushing other elements away?
✍️ Practice
- Build a box and give it different padding, border and margin values; watch each change.
- Open dev tools and inspect the box model of three elements on a real website.
🏠 Homework
- Draw the box model from memory and label all four layers.