Colours and Units
CSS supports several ways to define colour and several kinds of length units, each suited to different situations — from fixed pixel sizes to layouts that scale with the viewport.
Defining Colour
Colours can be named, defined as hexadecimal codes, or built from red/green/blue or hue/saturation/lightness values. HSL is often the easiest to reason about when creating colour variations, since adjusting lightness alone gives you lighter or darker shades of the same hue.
.box-a { background: red; }
.box-b { background: #ff0000; }
.box-c { background: rgb(255, 0, 0); }
.box-d { background: hsl(0, 100%, 50%); }
.box-e { background: rgba(255, 0, 0, 0.5); } /* 50% transparent */
Absolute vs Relative Units
Pixels are an absolute unit — a fixed size regardless of context. Relative units scale based on something else, which is essential for responsive, accessible designs that respect a user's font-size preferences.
- px — a fixed pixel size, doesn't scale with user preferences.
- % — relative to the parent element's size.
- em — relative to the current element's font size.
- rem — relative to the root (html) element's font size, avoiding compounding.
- vw / vh — relative to 1% of the viewport's width/height.
Common Mistakes
- Using px for font sizes exclusively, which ignores a user's browser-level font size preferences.
- Confusing em (relative to the current element) with rem (relative to the root), leading to unexpected compounding sizes in nested elements.
- Forgetting that percentage widths are relative to the parent container, not the whole page.
- Using rgba with an alpha value outside the 0-1 range.
Professional Tip
Use rem for font sizes and major spacing so your whole layout scales predictably if a user changes their browser's default font size — an important accessibility consideration.
Your Turn
Create three boxes with background colours defined using hex, rgb, and hsl respectively, each sized with rem units, and compare how easy each format is to adjust.
Mini Quiz
Which unit is relative to the root element's font size, avoiding compounding in nested elements?
rem (root em) always refers back to the html element's font size, so it stays predictable no matter how deeply an element is nested.