CSS Color Functions & Variables
Master modern CSS color functions and custom properties to create dynamic, maintainable, and flexible color systems in your web projects.
Modern CSS Color Functions
rgb() & rgba()
rgb(239, 68, 68)
rgba(239, 68, 68, 0.7)
color: rgb(239, 68, 68);
background: rgba(239, 68, 68, 0.7);
color: rgb(239 68 68);
background: rgb(239 68 68 / 0.7);
hsl() & hsla()
hsl(217, 91%, 60%)
hsla(217, 91%, 60%, 0.7)
color: hsl(217, 91%, 60%);
background: hsla(217, 91%, 60%, 0.7);
color: hsl(217 91% 60%);
background: hsl(217 91% 60% / 0.7);
oklch() - The Future
oklch(0.7 0.15 180)
oklch(0.5 0.2 330)
color: oklch(0.7 0.15 180);
background: oklch(0.5 0.2 330);
L: Lightness (0-1) | C: Chroma | H: Hue (0-360)
color() Function
color(display-p3)
color(rec2020)
color: color(display-p3 0.8 0.2 0.6);
background: color(rec2020 0.4 0.8 0.3);
Wide gamut color spaces for modern displays
CSS Custom Properties (Variables)
Basic Color Variables
Primary
Success
Danger
:root {
--primary: #2563eb;
--success: #10b981;
--danger: #ef4444;
}
.button {
background: var(--primary);
}
Advanced Color Systems
:root {
--blue-h: 217;
--blue-s: 91%;
--blue-100: hsl(var(--blue-h) var(--blue-s) 95%);
--blue-500: hsl(var(--blue-h) var(--blue-s) 60%);
--blue-900: hsl(var(--blue-h) var(--blue-s) 20%);
}
Practical Applications
Theme Switching
Dark Theme
Light Theme
[data-theme="dark"] {
--bg: #1f2937;
--text: #f9fafb;
}
Dynamic Transparency
Solid Color
50% Transparent
--primary-rgb: 37 99 235;
background: rgb(var(--primary-rgb) / 0.5);
Color Manipulation
Base Color
Lighter Variant
--hue: 270;
--base: hsl(var(--hue) 70% 50%);
--light: hsl(var(--hue) 70% 70%);
Best Practices & Tips
✓ Do
- •Use semantic variable names (--primary, --success, --text-muted)
- •Create color scales with consistent naming (--blue-100 to --blue-900)
- •Use HSL for easier color manipulation and theming
- •Leverage CSS custom properties for dynamic themes
- •Consider oklch() for future-proof, perceptually uniform colors
✗ Don't
- •Hardcode color values throughout your CSS
- •Use generic variable names (--color1, --color2)
- •Mix different color notations inconsistently
- •Forget to provide fallbacks for newer color functions
- •Overuse CSS variables where static values suffice
Browser Support & Fallbacks
Well Supported
- ✓ rgb(), rgba(), hsl(), hsla()
- ✓ CSS Custom Properties
- ✓ Modern space-separated syntax
- ✓ Alpha with slash notation
Limited Support
- ⚠ oklch(), color() functions
- ⚠ Wide gamut color spaces
- ⚠ color-mix() function
Progressive Enhancement Example
color: #3b82f6;
color: color(display-p3 0.2 0.4 0.9);
@supports (color: oklch(0.7 0.15 200)) {
color: oklch(0.7 0.15 200);
}