Course contentsShow
← Web Development
Lesson 475 of 2,9828. Advanced CSS Selectors and FeaturesFree lesson

Dark Mode with Custom Properties

Implementing dark mode by switching custom property values with prefers-color-scheme media query.

Dark Mode with Custom Properties

What you'll learn: How to seamlessly switch between light and dark color schemes by changing custom property values based on user preferences.

The Core Idea

Dark mode isn't about writing entirely separate stylesheets—it's about intelligently swapping color values. By combining CSS custom properties with the prefers-color-scheme media query (which you learned earlier), you can update your entire site's appearance by reassigning just a handful of variables.

Think of custom properties as your site's "color palette slots." Instead of painting every element manually twice (once for light, once for dark), you define colors like --bg-color and --text-color once, then simply refill those slots when the user's preference changes.

How It Works

You declare your default (light mode) colors at the :root level, then use a prefers-color-scheme: dark media query to override those same custom properties with dark-friendly values:

:root {
  --bg-color: white;
  --text-color: #333;
  --accent-color: blue;
}

@media (prefers-color-scheme: dark) {
  :root {
    --bg-color: #1a1a1a;
    --text-color: #e0e0e0;
    --accent-color: #66b3ff;
  }
}

body {
  background-color: var(--bg-color);
  color: var(--text-color);
}

a {
  color: var(--accent-color);
}

When a user's system is set to dark mode, the browser automatically applies the media query block, updating all three custom properties. Every element using var() instantly reflects the new values—no additional work required!

Why This Matters

This pattern keeps your dark mode implementation maintainable and scalable. Change one variable definition, and hundreds of elements update automatically. No duplicate selectors, no fragile overrides.

Key Takeaway: Dark mode with custom properties means defining your colors as variables once, then swapping their values inside a prefers-color-scheme media query—letting the entire interface adapt automatically.