A Simple prefers-color-scheme CSS Dark Mode

Dark and light mode with CSS prefers-color-scheme

Dark and Lighgt mode

Dark and light mode on websites and apps is more popular than ever before and in this article we will tell you a little bit about how you can use dark and light mode with prefers-color-scheme.

What Is the prefers-color-scheme Media Query

The prefers-color-scheme CSS media feature is used to detect if the user has requested a light or dark color theme.

There are two prefers-color-scheme values to choose from:

  • light - the user has expressed preference for a page that has a light mode or has not expressed an active preference
  • dark - the user has expressed preference for a page that has a dark mode

If we want to allow our website switch to dark mode, for users who prefer dark mode and find it more pleasant.


/* by default we have light mode styling */
.example {
  background-color: #fff;
  color: #000;
}

/* if user switches the system settings to dark mode */
/* this media query will be applied */
@media (prefers-color-scheme: dark) {
  .example {
    background-color: #000;
    color: #fff;
  }
}

Using above example we have have a dark mode support.


/* Light mode */
:root {
   --body-bg-color: #FFFFFF;
   --body-text-color: #000000;
}

/* Dark mode */
@media (prefers-color-scheme: dark) {
   :root {
       --body-bg-color: #000000;
       --body-text-color: #FFFFFF;
   }
}

In the CSS above, --body-bg-color and --body-text-color are the CSS variables. As you can see, they contain different values for both modes. On a light mode, I set a white background with black text. On a dark mode, I set a black background with white text.

What is the best way to save light and dark mode settings?

Personally, I recommend saving the settings in localstorage.

localStorage allows us to create and keep a variety of data on the client side. Cookies are sent to the server with each HTTP request and are processed on the server side. Therefore, localStorage is an obvious option for saving user settings.

The color-scheme

Including the color-scheme meta tag in the document tells the browser that the document supports light, dark, or both modes. This is necessary because some system UI elements, like form controls and scrollbars, don’t adjust well to dark mode.

Add color-scheme meta tag in your head, then add light dark inside of content attribute like below:

content="light dark"

Now your website tells the browser that the document supports light, dark, or both modes!

Source:

Post a Comment

0 Comments