Use CSS prefers-color-scheme to make your website more sustainable

Michael Andersen
2 min readSep 11, 2021

--

Using your phone at night, it’s so peaceful, you’ve made your phone as dull as possible, much easier to look at, with a dark theme, minimum brightness and all, and that’s when you decide to open a link your friend sent you. And here it comes, the light theme of the website blinding you momentarily and ruining all the fun you were having using your phone.

We’ve all been there and it’s brutal. You definitely don’t want to do that to your users and that is why the CSS Working group released prefers-color-scheme seeing the growing popularity of dark mode.

What is prefers-color-scheme?

prefers-color-scheme is a CSS media query that detects the user’s current theme preference indicated through the operating system or user agent settings. Developers can then customize the look of their website for a dark or light theme as to provide the best UX to all their users.

It can have the following two values:

1. Light: Indicates that the user prefers a light theme or no active preference has been expressed.

2. Dark: Indicates that the user prefers a dark theme

As media queries go, you can change the appearance of any element in your site to match the preferred theme. This means you can not only provide a good text contrast but also alter your whole site for the people who want or “need” their screens to be dark. For example, you can reduce the opacity of images on your site to make them easier to look at, you can change the logo on your website to match the style better, vectors and resources can be better suited accordingly, and much more.

Thus, prefers-color-scheme is not only beneficial for users but also for developers who don’t want to sacrifice the look and branding of their website just because of a different user preference.

How to use prefers-color-scheme?

Below is a simple code example of prefers-color-scheme usage:

/* Light mode */
@media (prefers-color-scheme: light) {
.class {
background-color: #9fffcb;
}
}
/* Dark mode */
@media (prefers-color-scheme: dark) {
.class {
background-color: #25a18e;
}
}

To read the full article please click the link to be redirected to our website: https://sustainablewww.org/principles/what-is-css-prefers-color-scheme-and-how-to-use-it-to-make-your-website-more-sustainable

--

--

Michael Andersen
Michael Andersen

No responses yet