Dark and Light Mode the Easy Way

There are many ways to have different color schemes on a site, specifically a light and dark mode. Some methods to achieve this are including media queries, or using javascript to apply a class to the DOM. These are fine, especially if you want the user to have control with a toggle.

But today we’re going over a simplified way with the handy light-dark CSS function.

Before we get to the final example, let’s go over how this is done using a media query with prefers-color-scheme.

body {
  background: white;

  @media (prefers-color-scheme: dark) {
    background: black;
  }
}

Let’s look at a demo:

See the Pen prefers-color-scheme example by Glenn Weatherson (@gweatherson) on CodePen.

But what’s so bad about that? Nothing! But when you start scaling a site, the media queries spread around like ants on a floor made of syrup.

Now, onto the light-dark() example.

root: {
  color-scheme: light dark;
}

body {
  background: light-dark(white, black);
}

Ahh, bliss, sure you have to define a root variable but there’s nothing like 1 liners afterwards.

Here’s the same demo above using light-dark() instead:

See the Pen prefers-color-scheme example by Glenn Weatherson (@gweatherson) on CodePen.

Back to all Writing