10. 6. 2023

Dark mode detection in CSS using prefers-color-scheme

Recently, dark mode has become increasingly popular. Users have the option to set their preferred visual scheme directly on their device, from mobile phones, tablets, Windows computers to MAC devices. If your site supports (or wants to support) both light and dark mode, it may be useful to detect user settings directly in CSS.

How to detect dark mode preference settings

To detect the preferred schema settings, we can use CSS media query , which you certainly use to detect other properties (typically the width of the responsive window). In this case, we will specifically use the prefers-color-scheme property.

Media query prefers-color-scheme for light / dark mode detection

Using the CSS code example below, you can detect both dark and light mode. This allows us to adjust the color of our user interface and adjust it to user preferences.

In the example, we customized two buttons, one light and the other dark. If the user has dark mode on, the light button will be dark and the dark button will be even darker. In the case of light mode, it will be the other way around, so we will lighten it.

CSS perefers-color-scheme support

At the time of writing, browser support is 84.23% . But we certainly don’t have to worry about using it, after all it’s more of a benefit for the user, when we can automatically detect its device settings. If we support both light and dark mode, there should always be the option to switch manually on the web. https://caniuse.bitsofco.de/embed/index.html?feat=prefers-color-scheme&periods=future_1,current,past_1,past_2&prefers-color-scheme=false

Automatic translation

This is an automatic translation of the original article in Czech.

Share

2 Comments

  1. Azook Khan Reply

    How to toggle dark/light using a button?

    I used this CSS method…

    @media (prefers-color-scheme: dark) {
    .light-button {
    background-color: #333;
    color: #fff;
    }

    .dark-button {
    background-color: #000;
    color: #ddd;
    }
    }

    I want to make toggle button enabe/disable darkmode…

    1. Pavel Kovář Post author Reply

      If you want to make toggle button with this functionality, you must use different method – root class method.

      Instead of @media (prefers-color-scheme: dark) { use .dark class on your element.

      Then, in your Javascript, you can dedect user’s preference and set .dark class when needed.

      if (window.matchMedia && window.matchMedia(‘(prefers-color-scheme: dark)’).matches) {
      // dark mode
      }

Leave a Reply

Your email address will not be published. Required fields are marked *