How to test dark mode preference in a browser
To provide the best experience to your users, you could rely on prefers-color-scheme
media query o understand whether they prefer dark mode or light:
@media (prefers-color-scheme: dark) { | |
// color variables for users which want your site to be dark | |
} | |
@media (prefers-color-scheme: light) { | |
// color variables for users which want your site to be light | |
} |
Probably you even need to fetch it from JavaScript:
if (window.matchMedia('(prefers-color-scheme: dark)').matches) { | |
console.log('User prefers dark mode on his device'); | |
} |
How to switch the preference for testing?
Thing is that up-to-the-moment browsers basically read Theme preference from the operating system. The same setting determines colors for all windows on the OS, not the only browser. On Windows/Mac you could spend some time to activate or deactivate the dark mode.
But on various Linux Desktop Environments e.g. Gnome Shell, Unity, KDE, XFCE it might be super tricky or not possible at all.
Luckily there is a universal way to do it.
Tested on Google Chrome 89.0.x and 91.0.x.
1) Open Developer tools
2) When DevTools are opened press Ctrl+Shift+P or Command+Shift+P (Mac). This will open so-called Command Control.
3) Type in the search "Show rendering"
4) Set the Emulate CSS media feature prefers-color-scheme to the value you want to debug
The preference will be activated only for the current tab.