Hello 👋

I'm Alejandro

A Web Engineer from Málaga, Spain based in London, UK

Detect color scheme with CSS

Dark and Light modes are becoming increasingly popular.

Today, many websites implement a switch that changes the color scheme from a light to a darker one and the other way around.

Giving your users this option is very beneficial for accessibility, as some people experience headaches or visual difficulties from bright screens, or have trouble reading for a long time on a light background.

In code

What if you could read the user preference and apply it to your website from CSS?

This is now possible thanks to the level 5 media queries specification, coming in form of a media query this way:

@media (prefers-color-scheme: dark) {
  /* dark mode styles here */
}

Where you can specify specific styles if the user has chosen to use the dark mode from the system preferences.

You can also do the same with light mode.

@media (prefers-color-scheme: light) {
  /* light mode styles here */
}

Or having a fallback in case the user have no preference.

@media (prefers-color-scheme: no-preference) {
  /* no-preference styles here */
}

In review

This is a clean and nice way to give your users the choice of appearance in which they would like to browse your website.

Likewise, I don't feel like this code is enough to give users the best experience, as they might want to switch from light to dark or the other way in a specific situation. So definitely keep the switch.

Read more about