typestar

Dark mode in CSS

Honouring the reader's system theme, with a manual override on top.

:root {
  --bg: #ffffff;
  --fg: #14161c;
}

@media (prefers-color-scheme: dark) {
  :root {
    --bg: #0b0c10;
    --fg: #e8e8ea;
  }
}

:root[data-theme="light"] {
  --bg: #ffffff;
  --fg: #14161c;
}

body {
  background: var(--bg);
}

How it works

  1. prefers-color-scheme reports the operating system setting.
  2. Keeping colors in variables makes the switch a few lines.
  3. A data-theme attribute lets a toggle win over the default.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
214
Tokens
60
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 40 seconds.

Type this snippet

Step 2 of 3 in Other media, step 11 of 13 in Styling components.

← Previous Next →