What is dark mode?

Dark Mode is also known as Dark Mode, as the name implies, it gives people the most intuitive feeling, is black. However, “dark mode” to achieve the ideal visual experience, it is not as simple as black background color, white text.

Google’s Material Design guide lists the first Design guideline for dark colors as “don’t use 100% pure black.”

UI designer Ilke Verrelst has pointed out that it is a basic design rule not to display plain black text on a plain white background and vice versa.

Why is that? Because pure white will reflect all wavelengths of light, and pure black will absorb all light, these are the two colors with the largest contrast, white on a white background, the text is too dazzling, so that the eye is too tired, and white on a black background, the text may be difficult to read.

How to make a “dark mode” that causes extreme comfort?

The amount of design and development involved was no less than a complete redesign.

The following is my actual combat experience, I hope to have some help and thinking for everyone compatible dark mode!

Step 1: How do I switch between dark and light colors during development? How about observing what you write in real time?

Let’s take Google Chrome as an example:

Open Google Browser, H5 debug, and select Console

Switch to dark mode

(Command + shift + P) — Enter dark in the search box

Note: There is no color change because Google H5 page does not support dark color mode!

Switch to light-colored mode

(Command + shift + P) — Enter light in the search box — select Emulate CSS GROUP-color-scheme: light

Step 2: Design a comparison table for excellent values

/ / the left: light color mode Right: dark patterns [[' # F3F7FE ', '# 303 d53], [' # E1ECFC', '# 35496 d], [' # 3 b81f5', '# 4171 c0], [' # 1266 ef', '# 4 b8fff],]Copy the code

Step 3: Start adapting

1, declare color-scheme

1.1 meta


1.2 CSS The CSS below can also achieve the effect of the meta declaration above

:root { color-scheme: light dark; }
Copy the code

Note: This statement is not intended to automatically adapt the page and only affects the browser default style. More information can be found in the W3C document CSS Color Adjustment Module Level 1.

2. Media inquiries

The CSS media feature detects whether the theme color of the system is set to dark mode or light mode.

Color value/background diagram

.bottom { color: #F3F7FE; // Width: 3.75rem; Height: 3.16 rem; padding: 0; background-image: url('.. /assets/footer.png'); // Background-repeat: no-repeat; background-size: 100% 100%; } @media (prefers-color-scheme: dark) { .bottom { color: #303D53; // Background-image: url('.. /assets/footer_dark.png'); // Background-repeat: no-repeat; background-size: 100% 100%; }}Copy the code

As we get more and more color values, more and more elements are involved. Code repetition rate is high, high coupling, not good batch maintenance and a series of problems!

Consider using CSS related plug-ins to solve this problem!

I recommend postCSs-darkmode as follows:

1) installation

$ npm install postcss-darkmode --save-dev
Copy the code

2) configuration

  • Ratio (number) : percentage of brightness adjustment. The default value is 10

  • AssignColors (array) : table of color substitutions, as in

    AssignColors: [["#ff6022", "#f25b20"], // #ff6022 replace #f25b20]Copy the code
  • IgnoreExistingDarkMediaQuery (Boolean) : does not handle the CSS file existing darmkmode Media Query in the rules of color, the default is true

  • IgnoreFiles (array): files that do not require dark transformation and support regular matching, for example, ignoreFiles: [“aaa.css”, /bbb.css/],

3) comments

  • /* darkmode: off */Disable all Darkmode translations for the whole block both before and after the comment. None of the CSS rule blocks in which this comment is placed do “dark mode” conversions
  • /* darkmode: ignore next */Disable Darkmode translations only for the next property. Ignore only the one immediately following this comment
  • /* darkmode: {#f00} */ Replace the next property with #f00Using the#f00Replace the value of the rule immediately following the comment

If it doesn’t work, you may be using a wrapper that filters out the comment before postCSs-DarkMode processes it. You can add an exclamation mark to the comment! , such as / *! Darmkmode: off */ to avoid comments being filtered.

4) use

use webpack

const path = require("path"); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); module.exports = { mode: "development", entry: "./src/index.js", output: { path: path.resolve(__dirname, "dist"), filename: "index.js", }, plugins: [ new MiniCssExtractPlugin({ filename: "css/style.min.css", chunkFilename: "css/[id].min.css", ignoreOrder: false, }), ], module: { rules: [ { test: /\.s[ac]ss$/i, use: [ { loader: MiniCssExtractPlugin.loader, options: { hmr: process.env.NODE_ENV !== "production", }, }, "css-loader", "sass-loader", { loader: "postcss-loader", options: { ident: "Postcss ", plugins: [require("postcss-darkmode")({ratio: 10, // Percentage of brightness adjustment, default is 10% assignColors: [[# D6AB56 "], / / the color unchanged [" # ff6022 ", "# f25b20"], / / # # ff6022 replacement for f25b20 [" # ff00a0 ", "# e60090"], [" # ff3333 ", "# e62e2e"]. [" # a1a1a1 ", "rgba (233, 237, 243, 0.1)"], [" rgba (244, 20, 20, 0.3) ", "# E91E63"],], ignoreExistingDarkMediaQuery: ["style.scss"], // Do not require dark converted files, support re matching splitFiles: {enable: false, // Whether to split dark styles into a new CSS file suffix: DestDir: ". Darkmode ", // dark CSS filename suffix, such as filename. CSS separated dark file: filename.darkmode. CSS destDir: "../../dist/ CSS ", // File output directory (relative to the current CSS file directory)}, inject: {enable: false, // Whether to switch the dark style injectSelector by class name instead of using media query mode: ".__darkmode__", // Toggle the dark-styled class name baseSelector: "HTML ", // To which selector this class name is to be added keepMediaQuery: If false, / / keep media query part of the code, and meet the needs of certain both code need},}),,,}},],},,,}};Copy the code

use gulp

const gulp = require("gulp"); const postcss = require("gulp-postcss"); const darkmode = require("postcss-darkmode"); gulp.task("css", () => { return gulp .src("*.css") .pipe( postcss([ darkmode({ ratio: // The percentage of brightness adjustment is 10% by default. If it is 0, it will not automatically adjust the brightness of assignColors: [// color change table, ["#ff6022", "#f25b20"], // replace #ff6022 with # f25B20 ["# ff00A0 ", "#e60090"], [" # ff3333 ", "# e62e2e"], [" # a1a1a1 ", "rgba (233, 237, 243, 0.1)"], [" rgba (244, 20, 20, 0.3) ", "# E91E63"],]. IgnoreExistingDarkMediaQuery: true, / / does not handle the CSS file existing darmkmode Media Query in the rules of color, the default is true ignoreFiles: ["style.scss"], // Don't need dark transformation files, support re matching splitFiles: {enable: false, // Whether to split dark styles into a new CSS file suffix: DestDir: ". Darkmode ", // dark CSS filename suffix, such as filename. CSS separated dark file: filename.darkmode. CSS destDir: "../../dist/ CSS ", // File output directory (relative to the current CSS file directory)}, inject: {enable: false, // Whether to switch the dark style injectSelector by class name instead of using media query mode: ".__darkmode__", // Toggle the dark-styled class name baseSelector: "HTML ", // To which selector this class name is to be added keepMediaQuery: },}),])). Pipe (gulp.dest("./dist/ CSS "); });Copy the code

3, picture adaptation

Using the Picture + Source TAB, set the url of the picture in different modes.

<picture> <! PNG "media="(color scheme: dark)" /> <! <img SRC ="light.png"/> </picture>Copy the code

4. Js listens to determine the current mode

This. IsDarkMode is used to do the detailed processing

<template>
  <div>
   <img src="image" />
  <div/>
<template/>

<script>
data () {
  return {
    isDarkMode: false,  
  }
},
 beforeMount() {
    const darkModeMediaQuery = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)');
    this.isDarkMode = darkModeMediaQuery.matches;
    darkModeMediaQuery.addListener(() => {
      this.isDarkMode = darkModeMediaQuery.matches;
    });
},

computed: {
   image: isDarkMode ? 'dark.png' : 'ligth.png'
},
<script/>
Copy the code