Skip to content
+91 89607 57615
Code Craft — web development and digital marketing
Lesson 822 min

Custom properties and dark mode

Move every colour into CSS variables, then give the site a dark theme that follows the visitor's device setting.

Taught by Sandesh Sahetiya

The video is part of the full course

In this lesson you will

  • Define and use CSS custom properties
  • Give a custom property a fallback value
  • Switch themes with prefers-color-scheme
  • Use color-scheme so built-in controls match

The bakery's colours are scattered through the stylesheet: the same brown appears in a dozen places. Custom properties, often called CSS variables, let you define a value once and use it everywhere. Change it in one place and the whole site follows. That makes a dark theme almost free.

Define once, on :root

styles.cssDownload
/* styles.css — Sunrise Bakery, lesson 8: custom properties and dark mode */

/* 1. Every colour is defined once, as a custom property on :root. */
:root {
  --bg: #fffaf2;
  --surface: #ffffff;
  --text: #2b2118;
  --heading: #8a3b12;
  --accent: #f2a83c;
  --header-bg: #fff4e0;
  --border: #f1dfc4;
  --muted: #6b5a4a;
  --radius: 12px;
  color-scheme: light dark;
}

/* 2. When the visitor's device is set to dark mode, swap the values.
      Nothing else in the stylesheet has to change. */
@media (prefers-color-scheme: dark) {
  :root {
    --bg: #1b1410;
    --surface: #261c16;
    --text: #f3e9df;
    --heading: #f7b267;
    --accent: #f2a83c;
    --header-bg: #2c2019;
    --border: #3d2d22;
    --muted: #c4b3a3;
  }
}
--bg: #fffaf2;
A custom property. The name must start with two dashes.
:root
The <html> element. Properties defined here are available everywhere on the page.
var(--bg)
Uses the value.
var(--radius, 8px)
Uses the value, or 8px if --radius isn't defined.
color-scheme: light dark
Tells the browser the page supports both, so scrollbars and form controls switch too.

Continue with the full course

The rest of this lesson, the narrated video, the PDF and the exercise are part of Web Development Foundations. One payment, lifetime access.

Already bought it? Sign in with the email you paid with.