Customize your application as per the DARK Mode from Device Setting

Adjust Application if the user enabled dark Mode on their Device, not from your web app

Anil Verma's photo
Anil Verma
ยทDec 19, 2021ยท
Customize your application as per the DARK Mode from Device Setting

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Many times, we have seen developers have created websites with dark mode with icon on their applications. Once we click on the dark mode icon, dark mode gets enabled. It is a good feature as we are providing it to users but there is a problem as below.

Problem-- Problem is when the user enables Dark Mode from device Setting, but not from your application on click of dark mode icon. In that case, also your website should work on dark Mode even dark mode is not enabled on your application.

Solution - You can access device color preference in a media feature called prefers-color-scheme.

@media (prefers-color-scheme: dark) {
  // Styles for a dark theme.
}

How to use prefers-color-scheme

Use as normal Media query in CSS

@media (prefers-color-scheme: dark) {
  body {
    background-color: black;
    color: white;
  }
}

Update CSS Variables Value for Dark Mode

html {
  --page-color: white;
  --ink-color: black;
}
@media (prefers-color-scheme: dark) {
  html {
    --page-color: black;
    --ink-color: white;
  }
}

Adjust SVG icons and Images visual appearance for Dark Mode

html {
  --page-color: white;
  --ink-color: black;
}
@media (prefers-color-scheme: dark) {
svg {
 stroke: var(--ink-color);
  fill: var(--page-color);
}

img {
    filter: brightness(.7) contrast(1.5);
  }
}

Swap Images as per Mode

if you've selected a dark theme in your settings,
then it will choose the first image, if not it will choose the second one.

<picture>
  <source srcset="dark-empire.jpg" media="(prefers-color-scheme:dark)">
  <img src="light-empire.jpg" alt="">
</picture>

Happy Learning... ๐Ÿ‘๐Ÿ‘๐Ÿ‘

ย 
Share this