Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect if Dark Mode is enabled on my website?

Tags:

javascript

css

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?

like image 943
Mehmet Ali Peker Avatar asked Jun 06 '18 22:06

Mehmet Ali Peker


2 Answers

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.

like image 83
Jordan H Avatar answered Nov 07 '22 12:11

Jordan H


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

like image 22
adriaan Avatar answered Nov 07 '22 14:11

adriaan