References

Color Schemes

classdescription
@light

☀️ Use descendant combinator html.light to apply a style in light mode.

@dark

🌙 Use descendant combinator html.dark to apply a style in dark mode.


Overview

Master uses an intelligent matching algorithm to make all styles support color schemes toggling, and the feature isn’t limited to color-related properties, which means you can also apply it in layout, sizing, typography, and more.

  • Using descendant combinator to apply a style based on color schemes.
  • Chaining style with @dark or @light.
  • Prioritizing @dark and @light suffix styles smartly.
Mountain
A mountain is an elevated portion of the Earth's crust, generally with steep sides that show significant exposed bedrock.
Mountain
A mountain is an elevated portion of the Earth's crust, generally with steep sides that show significant exposed bedrock.
<div class="f:gray-80@light f:gray-20@dark"></div>

Basic usage

  • set bg:fade-50 on default (overrided if set @dark or @light properties and set its related-mode).
  • set bg:fade-20 on dark mode.
  • set bg:fade-80 on light mode.
<div class="bg:fade-50 bg:fade-20@dark bg:fade-80@light "></div>

Setup

The most common practice is to provide and store the user’s preference, it is unlikely to rely solely on CSS prefers-color-schemes to implement a color schemes.

const storagedTheme = localStorage.getItem('theme');
const htmlClassList = document.documentElement.classList;
const DARK = 'dark';
const LIGHT = 'light';
const isDark = storagedTheme === DARK
    || !storagedTheme && window.matchMedia('(prefers-color-scheme: dark)').matches;

Detect user preferences

htmlClassList.toggle(LIGHT, !isDark);
htmlClassList.toggle(DARK, isDark);
if (!storagedTheme) {
    localStorage.setItem('theme', isDark ? DARK : LIGHT);
}

Toggle and storage theme

Current theme is .

<button id="theme-toggle">toggle theme</button>
const toggleTheme = () => {
    const theme = localStorage.getItem('theme');
    const htmlClassList = document.documentElement.classList;
    const isDark = theme === 'dark';
    htmlClassList.toggle('dark', !isDark);
    htmlClassList.toggle('light', isDark);
    localStorage.setItem('theme', isDark ? 'light' : 'dark');
};
document.getElementById('theme-toggle')
        .addEventListener('click', toggleTheme, { passive: true })

Warning ! the following are the most common access errors in localStorage, which will cause the storage event to fail to trigger, etc.

// Don't do this !
localStorage.theme = 'light';

© Aoyue Design LLC.
關於此頁的問題
編輯自AronLola