HomeTutorsContact

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

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.

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

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


Tags

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

Gulshan Saini

Fullstack Developer

Subscribe to our newsletter!

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

Related Posts

How to create simple theme switcher in CSS and JavaScript?

June 07, 2020
2 min
© 2020, All Rights Reserved.

Quick Links

Advertise with usContact Us

Social Media