All Topics
Visual Considerations
Prefers Color Scheme

Prefers Color Scheme

Similar to prefers-reduced-motion, there is also a CSS Media Query for styling users’ preferred color scheme between light or dark mode: prefers-color-scheme (opens in a new tab). Color schemes could be an accessibility issue for someone with light sensitivity.

Support is pretty good (opens in a new tab) and you could always make a custom toggle for any platforms that are slow on support. On a Mac, the setting to change the mode is under System Settings > Appearance.

Here is what the CSS code looks like:

.theme-a {
  background: #dca;
  color: #731;
}
@media (prefers-color-scheme: dark) {
  .theme-a.adaptive {
    background: #753;
    color: #dcb;
    outline: 5px dashed #000;
  }
}

And just like Reduced Motion, you can match the prefers-color-scheme setting with JavaScript matchMedia. Say light is your default theme, and you watch to match on dark mode:

const darkModeQuery = matchMedia('(prefers-color-scheme: dark)');
  let userPrefersDarkMode = true;
 
  function handleDarkModeChanged() {
    if (darkModeQuery.matches) {
      /* adjust color and other theme style properties */
      userPrefersDarkMode = true;
    } else {
      /* standard theme */
      userPrefersDarkMode = false;
    }
  }
  darkModeQuery.addEventListener('change', handleDarkModeChanged);
  
  handleDarkModeChanged();

You can do some really cool things with matchMedia along with managing state in a JavaScript app like in this docs website’s theme (Nextra / built with React (opens in a new tab)). And if you need to target code or media that you have less control over–or you’re in a more vanilla web stack–matchMedia could be a nice tool to have in your back pocket.

A reminder about contrast

Don’t forget to check color contrast in dark mode! In addition to the basic usability of form controls and other components in dark mode, your text and other components need to have accessible contrast ratios.

Before we had prefers-color-scheme, there was Windows High Contrast Mode (opens in a new tab). And this still exists! It would be worth testing if you have any site traffic on Windows, which most sites do. You will likely find some overlap with your styles for generic dark mode.