Lessons · HTML and CSS · the box model
The box model
Every element is a box: content, then padding inside the border, then the border, then margin outside it. Background paints the content and padding, never the margin.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Every 'why is there a gap here' and 'why does this not fit' is the box model. Once you can see the four layers, layout stops being guesswork.
How to think about it
Draw the four rings. Padding is breathing room inside the box; margin is distance from the neighbours. When something is too wide, add up content plus padding plus border.
Worked example
<div class="box">Content</div>A box to measure.
.box { width: 200px; padding: 20px; border: 5px solid rgb(0, 0, 0); margin: 10px; }Content 200 wide, 20 of padding each side, 5 of border each side: 250px on the page. The margin is outside that..box { background: rgb(230, 230, 230); }The background fills the content and the padding. The margin stays clear.Your turn
Add breathing room inside the box's border.
.box { : 16px; }Write a page and watch it render
The trap
Adding padding to make a box roomier and finding it wider than its column. By default, padding is added to the width rather than taken from it.