Write JavaScript like a pro. Javascript Icon

Follow the ultimate JavaScript roadmap.

Applying Dark Mode Styles in CSS

Learn how to write CSS selectors and tell the browser’s user agent (UA) which theme you prefer as an author, whilst letting the user decide based on their system preferences.

There are two things we need to understand here.

The first, writing CSS for both light and dark colour schemes…

And second, telling the UA which theme we prefer and can be used as a default.

Want to detect Dark Mode in your JavaScript? Read “Detecting Dark Mode in JavaScript” after.

To write CSS is fairly simple, we adopt a media query and put the code we want to appear inside the theme inside it.

For example, to supply CSS for dark theme:

@media screen and (prefers-color-scheme: dark) {
  p {
    color: #fff;
  }
}

And similarly, a light theme:

@media screen and (prefers-color-scheme: light) {
  p {
    color: #000;
  }
}

Combining the two, you could end up with something like this - writing with one theme in mind and the other as the ‘default’:

p {
  color: #000;
  @media screen and (prefers-color-scheme: dark) {
    color: #fff;
  }
}

That’s pretty much it. Now, which do you prefer for your website - light or dark?

You, as the site author, have the opportunity to guide the browser into a default theme.

To learn a bit more, you can deep-dive on Dark Mode on Web.dev

To do this, we simply pass in dark or light as the first option into a meta tag:

<meta name="color-scheme" content="dark light">

The above approach tells the browser to prefer dark and then use light if the user prefers it.

You can swap the content="dark light" to content="light dark" if you support both themes and prefer a light theme default.

Alternatively, you can supply this information as a CSS selector instead of a <meta> tag by targeting the :root {} and supplying the color-scheme property:

:root {
  color-scheme: light dark;
}

That’s it! You’re fully equipped to provide default dark or light mode themes to your users, and also write the styles however you see fit.

🏆 Want to learn more modern web practices? Check out our new JavaScript courses if you’re serious about taking your skills to the top.

Thanks for reading, enjoy, and happy coding!

Learn JavaScript the right way.

The most complete guide to learning JavaScript ever built.
Trusted by 82,951 students.

Todd Motto

with Todd Motto

Google Developer Expert icon Google Developer Expert

Related blogs 🚀

Free eBooks:

Angular Directives In-Depth eBook Cover

JavaScript Array Methods eBook Cover

NestJS Build a RESTful CRUD API eBook Cover