How can I detect if Dark Mode is enabled on my website?
This is now possible as WebKit has added support for the prefers-color-scheme
CSS media query. You can use it like so:
@media (prefers-color-scheme: dark) {
body { background: black; }
}
Or in JavaScript:
function isDarkModeEnabled() {
return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
}
Read more about Dark Mode Support in WebKit. This is available as of Safari 12.1, see Can I use... for the latest info on browser support.
If you want to detect if a user prefers dark mode via JavaScript you can use matchMedia
:
const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
Browser support: https://caniuse.com/#feat=prefers-color-scheme