Night mode vs. light mode

Many websites now support night mode, switching back and forth between light-colored modes. Recently, I found a very simple way to do a project, and I want to share it with you. This is achieved by setting the global style of the body and changing the className.

Let me show you the effect first

The first step is to set the global style

// Light color mode
body {
  --primary-color: #ff0064;
  --sun-color: #eec413;
  --link-color: #4299e1;
  --border-radius: 2px;
  --bg: #fff;
  --bg-second: #fff;
  --rgb-bg-second: rgba(255.255.255);
  --bg-body: #e7eaee;
  --bg-footer: #292525;
  --bg-code: #f8f8f8;
  --blockquote-color: #fff;
  --main-text-color: rgba(0.0.0.0.85);
  --second-text-color: rgba(0.0.0.0.65);
  --disable-text-color: rgba(0.0.0.0.35);
  --border-color: #e5e6eb;
  --box-shadow: 0 1px 3px rgb(18 18 18/10%);
  --scrollbar-bg: #dadada;
  --comment-editor-border-color: #d9d9d9;
  --comment-editor-disable-bg: #f5f5f5;
  --global-bg-opacoty: 0.75;
}
// Dark mode
body.dark {
  background: var(--bg);
  --sun-color: #e684af;
  --bg: #282c35;
  --bg-second: #363c48;
  --rgb-bg-second: rgba(54.60.72);
  --bg-body: var(--bg);
  --bg-footer: var(--bg);
  --bg-code: rgba(115.124.153.0.2);
  --blockquote-color: #fff;
  --main-text-color: hsla(0.0%, 100%, 0.85);
  --second-text-color: hsla(0.0%, 100%, 0.65);
  --disable-text-color: hsla(0.0%, 100%, 0.45);
  --border-color: hsla(0.0%, 100%, 0.2);
  --box-shadow: 0 2px 15px 0 rgba(26.26.27.0.637);
  --scrollbar-bg: var(--bg-second);
  --comment-editor-border-color: var(--border-color);
  --comment-editor-disable-bg: var(--border-color);
  --global-bg-opacoty: 0.25;
}
Copy the code

The second step is to change the body class name

const checkTheme = () = > {
    if (!document.body.className) {
       document.body.className = "dark"
    } else {
        document.body.className = ""}}Copy the code

Change the className of the body, and then you can render the little sun or moon by determining the className of the body.

Last step: The next background styles, font styles all reference global styles

Var (), class style, just to show you

body {
  background-color: var(--bg);
}
Copy the code

You can just do it. That’s about it. Be sure to use var() to refer to all styles there. For those who don’t understand var(), the var() function can replace any part of the value in any attribute in an element. Inside the parentheses is the name of our global style.

That’s all, everyone has a better way to remember to share with me! thank you