This site uses third-party cookies, learn more or accept
dark light

Check the OS color scheme: prefers-color-scheme in CSS

Written by Max Pelic on

There's a new CSS media query in development called prefers-color-scheme. It's a variable that will be set to dark if the OS has dark mode enabled, will be set to light if the light mode is enabled, and no-preference if the user has not made a preference.

As of May 2019, support is limited for this (see caniuse.com), but it's in development and should be implemented in the future.

Personally, I'm super excited about this feature. As you may know, I currently have a dark/light mode toggle button on my blog, and I'd love to have it default to whatever the user prefers instead of having them have to change it when they visit this site.

The check will work something like this:

1/** default CSS **/

2
3@media (prefers-color-scheme:dark){
4 /** dark mode css **/
5}
6@media (prefers-color-scheme:light){
7 /** light mode **/
8}

Here's a link to the documentation: developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme

Share this article:

Previous Article: MySQL results not updating? Check the query cache

Next Article: Dark/Light mode - HTML and CSS, JavaScript if you'd like