Box model, units and text
Units and colours
Goal: Choose between px, em, rem, % and viewport units and write colours in hex, rgb and hsl · 10 min
Absolute unit: px is a CSS pixel, a fixed size. Relative units adapt:
| unit | relative to | example |
|---|---|---|
em | the font size of the element (for font-size itself: of the parent) | padding: 1.5em |
rem | the font size of the root element (usually 16px) | font-size: 1.25rem = 20px |
% | the parent's size | width: 50% |
vw / vh | 1% of the viewport width / height | height: 100vh |
Why rem? Users can raise their default font size for readability. Sizes in rem grow with it; sizes in px do not. Use rem for text and spacing, px for thin details such as borders.
Colours can be written four ways:
- Names:
red,teal,rebeccapurple - Hex:
#ff8800= red 255, green 136, blue 0; short form#f80equals#ff8800 - rgb:
rgb(255 136 0)orrgba(255, 136, 0, 0.5)with transparency - hsl:
hsl(30 100% 50%): hue (0–360° around the colour wheel), saturation, lightness. Handy for making lighter or darker variants.
Contrast matters. WCAG asks for a contrast ratio of at least 4.5:1 for normal text (3:1 for large text). Light grey on white often fails.
Worked example: From em to pixels
- The root font size is 16px. A paragraph has font-size: 1.25rem → 20px.
- Inside it, padding: 1.5em → 1.5 · 20px = 30px (em uses the element's own font size).
- A child width: 50% of a 400px parent = 200px.
html { font-size: 16px; }
p {
font-size: 1.25rem;
padding: 1.5em;
}