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.
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 preferencelight
- user opted for light themedark
- 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.
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`) }) }
As of June 2020, the prefers-color-scheme
is supported mostly in popular browsers as we can see in the screenshot below - source: caniuse