9. The Box Model
Every HTML element is a rectangular box with four layers. From inside out: the content, the padding (space inside the border), the border, and the margin (space outside the border). Understanding the box model explains almost every spacing question in CSS. Add box-sizing: border-box so that width includes padding and border, which makes sizing predictable.
Key points
- padding pushes content away from the border.
- margin pushes other elements away from this one.
- Shorthand: margin: 10px 20px; means 10px top and bottom, 20px left and right.
- width and max-width limit how wide a box can be.
- margin: 0 auto; centres a box that has a width.
Example: Padding, border and margin
<div class="box">Box one</div>
<div class="box">Box two</div>
<style>
* { box-sizing: border-box; }
.box {
width: 260px;
padding: 20px;
border: 3px solid black;
margin: 16px auto;
background: #f2f2f2;
text-align: center;
}
</style>
Show explanation
Each box is 260px wide including padding and border, and is centred by margin: auto. Change padding to 40px to see the inside space grow.
Try it yourself
Edit the code below and press Run. The result appears in the preview underneath.
PREVIEW