How to detect if OS X is in dark mode in browsers?

2019-03-08 19:28发布

问题:

Similar to "How to detect if OS X is in dark mode?" only for browsers.

Has anyone found if there is a way to detect if the user's system is in the new OS X Dark Mode in Safari/Chrome/Firefox?

We would like to change our site's design to be dark-mode friendly based on the current operating mode.

回答1:

New standard is registered on W3C in Media Queries Level 5.

NOTE: currently only available in Safari Technology Preview Release 68

In case user preference is light:

/* Light mode */
@media (prefers-color-scheme: light) {
    body {
        background-color: #000;
        color: white;
    }
}

In case user preference is dark:

/* Dark mode */
@media (prefers-color-scheme: dark) {
    body {
        background-color: #000;
        color: white;
    }
}

There is also the option no-preference in case a user has no preference. But I recommend you just to use normal CSS in that case and cascade your CSS correctly.

EDIT (7 dec 2018):

In Safari Technology Preview Release 71 they announced a toggle switch in Safari to make testing easier. I also made a test page to see the browser behaviour.

If you have Safari Technology Preview Release 71 installed you can activate through:

Develop > Experimental Features > Dark Mode CSS Support

Then if you open the test page and open element inspector you have a new icon to toggle Dark/Light mode.

-

EDIT (11 feb 2019): Apple ships in the new Safari 12.1 dark mode



回答2:

This is currently (September 2018) being discussed in "CSS Working Group Editor Drafts". Spec has launched (see above), available as a media query. Something has already landed in Safari, see also here. So in theory you can do this in Safari/Webkit:

@media (prefers-dark-interface) { color: white; background: black }

But it seems that this is private. On MDN a CSS media feature inverted-colors is mentioned. Plug: I blogged about dark mode here.



回答3:

I searched though Mozilla API, they don't seem to have any variables corresponding to the browser-windows color. Though i found a page that might help you: How to Use Operating System Styles in CSS. Despite the article-header the colors are different for Chrome and Firefox.



标签: css macos safari