Topic 8 of 30
Colors
Overview
CSS provides multiple ways to specify colors — keywords, hex, RGB, HSL, and modern oklch/oklch. HSL is preferred for design systems because it's intuitive to reason about hue, saturation, and lightness.
Syntax
css
color: red; /* Named */
color: #FFD700; /* Hex */
color: #FFD7004D; /* Hex with alpha */
color: rgb(255, 215, 0); /* RGB */
color: rgba(255, 215, 0, 0.3); /* RGBA */
color: hsl(51, 100%, 50%); /* HSL */
color: hsla(51, 100%, 50%, 0.5);/* HSLA */
/* Modern (wide gamut) */
color: oklch(0.85 0.2 85);
/* CSS custom properties */
:root { --brand: hsl(51, 100%, 50%); }
h1 { color: var(--brand); }Common Pitfalls
- HSL is much easier to create accessible color palettes with — you can lighten/darken by just changing L%.
- Ensure text/background contrast ratio is at least 4.5:1 for WCAG AA compliance.
- Interview tip: currentColor keyword inherits the element's color — useful for icon SVGs: svg { fill: currentColor; }
Real-World Example
A design token system with CSS custom properties:
example
css
:root {
/* Brand */
--color-primary: hsl(51, 100%, 50%); /* Gold */
--color-primary-dim: hsla(51, 100%, 50%, 0.15);
/* Surfaces */
--color-bg: hsl(0, 0%, 6%);
--color-surface: hsl(0, 0%, 12%);
--color-border: hsl(0, 0%, 20%);
/* Text */
--color-text: hsl(0, 0%, 95%);
--color-muted: hsl(0, 0%, 60%);
}
.card {
background: var(--color-surface);
border: 1px solid var(--color-border);
color: var(--color-text);
}
.badge {
background: var(--color-primary-dim);
color: var(--color-primary);
}