How to detect color preference based on user settings?

By Gulshan Saini
Published in HTML
June 08, 2020
1 min read

Most computers and smart devices have the option to adjust system-wide colors. You can switch between light and dark modes using the operating system settings. Browsers too have the option to change site colors, fonts, font sizes, zoom, contrast levels, etc. for a very long time.

To make web more accessible, it makes sense to adjust site colors based on user preference.

You can detect the preferred color scheme either by CSS or using JavaScript.

Detecting preferred color scheme using CSS

The prefers-color-scheme media feature reflects the user’s desire that the page uses a light or dark color theme. It accepts following values:

  • no-preference - user has not set any preference
  • light - user opted for light theme
  • dark - user opted for dark theme
@media (prefers-color-scheme: dark) {
  // dark theme styles goes here
@media (prefers-color-scheme: light) {
  // light theme styles goes here

Tip: To reduce the size of CSS, you can split the css files in three parts i.e. all.css, light.css and dark.css. Load light.css or dark.css conditionally based on user preference.

Detecting preferred color scheme using JavaScript

You can even get the preferred color scheme using JavaScript and take necessary action.

if (
  window.matchMedia &&
  window.matchMedia('(prefers-color-scheme: dark)').matches
) {
  // set theme to dark

Tip: Using JavaScript, you can even listen to event when mode changes from light to dark or vice-versa

if (window.matchMedia) {
  matchMedia('(prefers-color-scheme: dark)').addListener(({ media }) => {
    alert(`${media.matches ? 'dark' : 'light'} mode`)

Browser support

As of June 2020, the prefers-color-scheme is supported mostly in popular browsers as we can see in the screenshot below - source: caniuse

prefers color scheme browser support
prefers color scheme browser support


Previous Article
How to create simple theme switcher in CSS and JavaScript?

Related Posts

How to create simple theme switcher in CSS and JavaScript?
June 07, 2020
2 min
Gulshan Saini

Gulshan Saini

Fullstack Developer



Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media