Colors and fonts
Colour and typography do most of the work of making a site look professional. Let's learn the tools, plus the cascade, the rule system behind the "C" in CSS.
Colour formats
HSL is the most human-friendly format. Keep the hue and change the lightness to get a whole palette:
Backgrounds and gradients
Fonts
font-family is a fallback stack: if the first font isn't available, the browser tries the next one. Always end with a generic family (serif, sans-serif, monospace).
Web fonts
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
<style> body { font-family: 'Inter', system-ui, sans-serif; } </style>display=swap shows a fallback font immediately and swaps in the web font when it loads, so text is never invisible.
Units
| Unit | Relative to | Use for |
|---|---|---|
px |
Screen pixels | Borders, small fixed details |
rem |
The root (html) font size, usually 16px |
Font sizes and spacing (respects user settings) |
em |
The current element's font size | Padding that scales with text |
% |
The parent | Widths |
vw / vh |
1% of viewport width/height | Full-screen sections |
ch |
Width of the "0" character | Readable line lengths (max-width: 65ch) |
The cascade: who wins?
When several rules target the same element, CSS decides in this order:
- Importance:
!importantwins (avoid it; it's a sledgehammer). - Specificity: more specific selectors win.
- Source order: with equal specificity, the last rule wins.
Specificity is scored as (ids, classes/attributes/pseudo-classes, elements):
| Selector | Score |
|---|---|
p |
0-0-1 |
.intro |
0-1-0 |
p.intro |
0-1-1 |
#main .intro |
1-1-0 |
style="…" |
beats all selectors |
Inheritance
Some properties (like color, font-* and line-height) are inherited by children. Others (like border, padding and background) aren't. That's why setting font-family on body styles the whole page.
Practice
Create a "profile card" with a gradient background header, a heading in a web-safe sans-serif stack at 1.5rem, body text at 1rem with line-height: 1.6, and a muted grey subtitle. Then use HSL to make a hover colour that's the same hue as your gradient but darker.
1.Which unit should you generally prefer for font sizes?
2..btn and button.btn both set a colour. Which wins?