Reference · module 5
The box model
Everything this module explains, on one page.
Padding, border, margin
Control the space inside and around an element.
- Every element is a box of layers. In the middle is the content; padding is space inside the box around it; border is the edge; margin is space outside that pushes other boxes away.
- padding: 16px adds 16 pixels on all four sides. padding: 8px 16px means 8 top and bottom, 16 left and right. margin takes values the same way.
- border needs a width, a style and a colour: border: 2px solid black. Background colour fills the content and the padding, but never the margin.
The mistake you are about to make
margin to add space inside a button
padding: 12px;
Both are just space, so either seems fine. margin sits outside the border and does not grow the clickable, coloured area — padding does.
Width and box-sizing
Predict how wide a box really is.
- width sets the width of the box. By default, box-sizing: content-box, that width is only the content: padding and border are added on top of it.
- So width: 200px with padding: 20px and a 5px border is 200 + 40 + 10 = 250 pixels wide on screen. This surprise breaks many layouts.
- box-sizing: border-box makes width include padding and border, so 200px means 200px on screen. Most projects set it for every element at the top of the stylesheet.
The mistake you are about to make
width: 100%; padding: 20px; → fits
box-sizing: border-box; width: 100%; padding: 20px;
100% sounds like exactly the available space. With content-box the padding is added on top, so the box overflows its parent by 40 pixels.
Which rule wins
Predict the result when several rules style the same element.
- When two rules with equal selectors set the same property, the one written later wins. p { color: red; } then p { color: blue; } gives blue text.
- A more specific selector beats a less specific one regardless of order. An id beats a class, and a class beats a tag: .note beats p even if p comes later.
- Some properties are inherited by children, like color and font-family: set them on body and all text follows. Box properties like padding and border are not inherited.
The mistake you are about to make
p { color: blue; } after .note { color: red; } → blue
.note wins → red
Later rules usually win, so the last one feels decisive. Order only breaks ties; a class selector is more specific than a tag and wins anyway.