22 min read
The Box Model
Every element is a box of content, padding, border and margin. Understand it, and spacing and sizes stop being a mystery.
Every Element Is a Box
| The four layers, from inside to outside | ||
|---|---|---|
What the browser shows
Try it: Change padding to 5px, then 40px — the space inside grows. Change margin to 0 — the boxes touch. Press F12 in your own browser and hover an element to see the four layers highlighted.
How Big Is the Box?
By default, width sets only the content width. Padding and border are added on top:
Total width = width + left and right padding + left and right border
For the box above: 220 + 20 + 20 + 4 + 4 = 268 px wide (plus the margin outside it).
box-sizing: border-box
The rule almost every site starts withCSS
* { box-sizing: border-box;}With border-box, width includes the padding and border — a 220px box stays 220px however much padding you add. This makes layouts far easier, so Kasun puts this rule at the top of style.css.
box-sizing
| content-box (default) | border-box |
|---|---|
| width = content only | width = content + padding + border |
| Adding padding makes the box wider | Adding padding squeezes the content; the box stays the same width |
| Hard to fit boxes into columns exactly | Easy: two 50% boxes really fit side by side |
Block and Inline Boxes
- Block boxes (div, p, h1, section, li) start on a new line and stretch the full width. Width, height, margin and padding all work.
- Inline boxes (a, span, strong, img) flow inside a line of text. Top and bottom margins do not push other lines away.
- display: inline-block gives an inline element a block's sizing — useful for buttons.
- display: none hides an element completely.
Practice
What is the order of the box model layers from the inside out?
More lessons in CSS · Next: Spacing, Borders and Sizing · Previous: Fonts and Text
