How can I detect if the user of my website is using macOS / Windows with Dark Mode enabled using JavaScript or CSS? Is this possible?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With