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