The Box Model
Every single HTML element, no matter what it is, is secretly a rectangular box made of four layers, from the inside out: content (the actual text or image), padding (empty space between the content and the border, like cushioning), border (a visible or invisible line around the padding), and margin (empty space OUTSIDE the border, pushing other elements away). This is the single most important idea in CSS layout nearly every 'why is there a weird gap here' bug comes down to confusing margin with padding, or forgetting how they stack. By default, when you set width: 200px on an element, that 200px only covers the CONTENT padding and border get added ON TOP, making the element wider than you expected. Setting box-sizing: border-box changes this so width includes padding and border too, making sizing calculations far more predictable most professional CSS resets apply this to every element right at the start of a project.
Why this matters
- ·Understanding the box model explains almost every spacing bug in CSS
- ·box-sizing: border-box makes width calculations predictable and easy to reason about
- ·Margin lets elements space themselves apart without needing empty spacer elements
Common mistakes
- ·Forgetting box-sizing: border-box makes width math confusing once you add padding
- ·Confusing margin (outside the border) with padding (inside the border) is an extremely common mistake
- ·Vertical margins between two elements can 'collapse' into just the larger one instead of adding together, surprising beginners
Frequently asked questions
It makes the width/height you set include padding and border, instead of adding on top of them this makes sizing much more predictable.
Practice questions
Question 1
Give a div 24px padding and a dashed border, using the internal method.
Question 2
Create two boxes with different margin values and compare the gap between them.
Quick check
Just for this topic answer honestly, then check yourself.
1 / 10
