preface

Over the past year, the concept of dark mode has taken off, and with system-level support, other major applications have been adapted, most of them offering portals that allow users to switch the entire theme for the most comfortable experience

Why dark mode?

I didn’t understand the problem at first. The black interface is not only difficult to recognize, but also increases the burden of development and UI. But if YOU think back, why did macOS and iOS introduce dark mode, Chrome, Gmail and other mainstream apps also provide features that support dark mode? There is still room for thinking behind it:

  • Eye! Yes, it is the legendary eye protection. At night, it can make the user’s eyes more comfortable and improve visibility
  • Significantly reduced power consumption (depending on the screen technology of the device)
  • Improve user experience in some special scenes (reading novels, watching videos)

Dark mode is supported by CSS

If we only want to change the color scheme of the site in dark mode, THEN CSS is a good way to do it if the system is in dark mode

In the CSS file, write the following media query code:

@media (prefers-color-scheme: dark) {
    /* Dark mode style code */
}
Copy the code

When the system is in dark mode, the styles in the media query will take effect by default

PC practice

Let’s start by creating an HTML file that looks like this:


      
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<style>
    @media (prefers-color-scheme: dark) {
        p {
            color: red
        }
    }
</style>
<body>
    <p>I turn red in dark mode</p>
</body>
</html>
Copy the code

I go to the browser, it’s black, okay, so let’s go to dark mode for the system, okay

Using Windows 10 as an example, we just need to choose Start – Settings – Personalization – Color – Default Application mode (dark).

Open the browser again, our style has worked successfully!

MAC users, starting with macOS Mojava, can also turn on dark mode

Mobile practices

Let’s take iPhone as an example. The code stays the same. Just turn on the dark mode in Settings – Display and Brightness.

Deficiency in

According to CanIUse.com, the support rate for the CSS property is 80% on all browsers, but not on IE and non-Chromium versions of Edge. So if your site is c-oriented and users have a wide variety of browsers, be sure to make it compatible

And users can not actively switch mode in the browser, can only rely on the system theme mode

Switch style sheets using JavaScript

To implement dark mode with JavaScript switching style sheets, we need to create two different style sheets for different themes (light and dark).

First, insert the default stylesheet in

<link id="theme" rel="stylesheet" type="text/css" href="light-theme.css" />
Copy the code

Then, create a button to toggle the stylesheet, as close to the top of the page as possible for the user to find it quickly

<button id="theme-toggle">Switch to dark mode</button>
Copy the code

Continue adding the following JavaScript snippet:

// The DOM callback is triggered when the DOM load is complete
document.addEventListener('DOMContentLoaded', () = > {const themeStylesheet = document.getElementById('theme');
    const themeToggle = document.getElementById('theme-toggle');
    themeToggle.addEventListener('click', () = > {// if it's light -> go dark
        if(themeStylesheet.href.includes('light')){
            themeStylesheet.href = 'dark-theme.css';
            themeToggle.innerText = 'Switch to light mode';
        } else {
            // if it's dark -> go light
            themeStylesheet.href = 'light-theme.css';
            themeToggle.innerText = 'Switch to dark mode'; }})})Copy the code

You can do it yourself, I won’t show it here, but is there room for optimization?

There are! Imagine a user switching to dark mode, then shutting down the site, only to return to the default theme on their second visit and have to manually switch again. However, we can use LocalStorage to solve the above problems quickly

Save the user’s selection in localStorage

LocalStorage can store key-value pairs, as shown below:

localStorage.setItem('theme'.'dark-theme.css');
Copy the code

Let’s make some optimizations to the previous code:

// The DOM callback is triggered when the DOM load is complete
document.addEventListener('DOMContentLoaded', () = > {const themeStylesheet = document.getElementById('theme');
    const storedTheme = localStorage.getItem('theme');
    if(storedTheme){
        themeStylesheet.href = storedTheme;
    }
    const themeToggle = document.getElementById('theme-toggle');
    themeToggle.addEventListener('click', () = > {// if it's light -> go dark
        if(themeStylesheet.href.includes('light')){
            themeStylesheet.href = 'dark-theme.css';
            themeToggle.innerText = 'Switch to light mode';
        } else {
            // if it's dark -> go light
            themeStylesheet.href = 'light-theme.css';
            themeToggle.innerText = 'Switch to dark mode';
        }
        // Save the user-selected theme
        localStorage.setItem('theme', themeStylesheet.href)  
    })
})
Copy the code

SessionStorage is not used here because the life cycle of sessionStorage only exists in the TAB page of the domain name. When the TAB page or browser is closed, sessionStorage will be cleared, but localStorage will not be deleted unless the user deletes it

As an aside, do you know what the maximum capacity of localStorage is? What happens when the maximum capacity is exceeded? Is there a solution?

It is important to note that localStorage strictly adheres to the same origin policy, and topics saved when you visit the site over HTTP will disappear when you visit the site over HTTPS

Toggle class names using JavaScript

If we only want to use one style sheet, we can also switch to dark mode

Add the following JavaScript snippet:

button.addEventListener('click', () = > {document.body.classList.toggle('dark');
    localStorage.setItem('theme'.document.body.classList.contains('dark')?'dark' : 'light');
});

if (localStorage.getItem('theme') = = ='dark') {
    document.body.classList.add('dark');
}
Copy the code

CSS file as follows:

/* Light mode */
body {
  background: #fff;
  color: # 000;
}

/* Dark mode */
body.dark {
  background: # 000;
  color: #fff;
}
Copy the code

As we know, the priority of CSS styles depends on the weight overlay of their selectors. Whichever weight is higher will display the corresponding style :(body = 1) < (body. Dark = 1 + 10 = 11)

! Important > Inline style > ID selector > Class, pseudo-class, attribute selector > Element, pseudo-element selector

References:

  • Add dark mode to your website with just a few lines of code
  • Household Energy Monitor : Prototype 1 (Design Assignment)