Using prefers-color-scheme to Support Dark Mode

With many operating systems now supporting an option for dark mode, most modern browsers now support a CSS media property called prefers-color-scheme that allows you to customize your site or application to the stated preference of the user. It is very easy to use and provides a great user experience.

Setting Up the Media Queries

First thing to do is set classes on whatever elements you would like to change based on the user's preference. For our simple example here we will just apply them directly to the <body> element.

<!doctype html>
<html>
<body class="prefers-light-schema prefers-dark-schema">
  <p>This is how we use prefers-color-scheme.</p>
</body>
</html>

Next in your stylesheet, set up the media queries to get the user preference and then set different rules for each.

@media (prefers-color-scheme: dark) {
  .prefers-dark-scheme {
    background: #333333;
    color: #CCCCCC;
  }
}
@media (prefers-color-scheme: light) {
  .prefers-light-scheme {
    background: #CCCCCC;
    color: #333333;
  }
}

Testing in Your Local Browser

In order to test this during development, you can force your browser to send either light or dark as your preference for color schema. In Google Chrome this is found in the Rendering tab next to the Console.

Now you can easily design and develop for the individual preferences of your users!