Stormblessed
Stormblessed

Reputation: 201

Is there a way to check what colors the browser themes of users are?

I recently updated my Mac to Mojave. In it, the computer now sends information to the browser as to whether Dark Mode is on, to use within CSS like in this example, which makes the text blue in <body> if it is on:

@media (prefers-color-scheme: dark) {
               body {
                   color: blue;
               }
            }

Some websites use this to set their tab icons to white or light gray if it's on. For example:

The New York Times sets its tab icon to white if Dark Mode is on

However, if the browser isn't set to a dark theme, it looks bad, so this is not a great way to check whether stuff should be light or dark:

The icon is barely visible

Is there any sort of way to get the color of tabs in a browser's theme in CSS or JavaScript, so as to implement a feature like this better?

Upvotes: 1

Views: 929

Answers (1)

L&#233;o
L&#233;o

Reputation: 33

Like with "width" and "height" media queries, you can set properties depending on the "prefers-color-scheme" property like that :

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

Note than you can also set variables along with properties that way :

root: {
    --text-color: black;
    --back-color: white;
}
body {
    color: var(--text-color);
    background: var(--back-color)
}
@media (prefers-color-scheme: dark) {
    root: {
        --text-color: white;
        --back-color: black;
    }
}

It's really cool. :)

The browsers support for this is pretty new and not on every browser (yet), you will have to choose if you prefer to wait a little bit or if you don't care :D https://caniuse.com/#search=prefers-color-scheme

You won't be able to get the exact color used by a user on his browser, simply because browsers are done differently and engines have to be a little standardized and can't implement some functionalities that will work only on their browser.

Upvotes: 1

Related Questions