DEV Community

Ayc0
Ayc0

Posted on โ€ข Edited on

4 1

Light/dark mode: the simple way

In the previous post, we've seen how to use the color-scheme html meta tag to benefit from the browser default themes.

In this post, weโ€™ll iterate on that and use our own styles.

CSS variables

CSS variables (documentation) are runtime variables that you can dynamically re-assign. For instance, consider this example:

:root {
  --color: orange;
}
.color-blue {
  --color: blue;
}
* {
  color: var(--color);
}
Enter fullscreen mode Exit fullscreen mode

By default, all elements will be in orange. But when wrapped in an element with the classname color-blue, their color will now be blue (and as usual in css, it cascades).

Media query

Media queries aren't only useful for responsive design and changing the layout based on the screen size. When using prefers-color-scheme, you can modify your rendering based on if your user prefer to view their website in light/dark mode.

End result

By combining both, you can create a color palette that will automatically adapt to your users preferences:

:root {
  --text: black;
  --background: white;
}

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

body {
  color: var(--text);
  background: var(--background);
}
Enter fullscreen mode Exit fullscreen mode

I'd still recommend adding a <meta name="color-scheme" content="light dark" /> in your HTML as seen in the previous post to have native inputs that will look good in dark mode.

Auth0

Auth0 now, thank yourself later. ๐Ÿ˜Œ

Level up your auth game! Our Auth0 plans just got a major upgrade. Now offering 25K MAUs, free Custom Domain, and more! Check out whatโ€™s new.

Learn more

Top comments (0)

๐Ÿ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay