Перейти до основного вмісту
← 🎨 CSS as a design system·Модуль B5 · Урок 5
ЗавданняBuild a dark-mode-aware page. :root tokens for light. @media (prefers-color-scheme: dark) :root overrides for dark. Add color-scheme: light dark to :root. body uses var(--bg), color var(--text). .card uses var(--surface) + border var(--border).

Темний режим через prefers-color-scheme

100 XP7 min
Теорія

Dark mode in 8 lines of CSS

:root {
  --bg: white;
  --text: oklch(0.20 0 0);
  --surface: oklch(0.98 0 0);
  --border: oklch(0.90 0 0);
}

@media (prefers-color-scheme: dark) {
  :root {
    --bg: oklch(0.18 0 0);
    --text: oklch(0.95 0 0);
    --surface: oklch(0.22 0 0);
    --border: oklch(0.30 0 0);
  }
}

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

prefers-color-scheme matches the user's OS setting. If they have macOS in dark mode, your site is dark. Light mode, your site is light. They flip the setting → your site flips automatically.

Custom properties bridge the gap — the COMPONENTS reference var(--bg), the THEME just changes what --bg resolves to.

Add color-scheme to opt in

:root { color-scheme: light dark; }

Tells the browser "this page supports both modes." Browser uses the right defaults for form controls (<input>, <select> get dark UI), scrollbar colors, and the <dialog> backdrop.

Without this, scrollbars stay light-themed on a dark page — looks broken.

Don't ship dark mode without testing it

Dark mode often surfaces:

  • Low-contrast text that was barely readable in light mode (now invisible).
  • Background images with white edges (visible on dark canvas).
  • Borders too dark to see.

Test BOTH modes in Chrome DevTools → Rendering → "Emulate CSS media feature prefers-color-scheme."

🔒

Зареєструйся щоб кодувати

Теорія відкрита всім. Інтерактивний редактор, живий перегляд і перевірка відкриваються з 7-денним безкоштовним trial — потрібна картка, скасування у будь-який час.

Реєстрація — безкоштовний trial →

Перші 10 уроків у кожному треку — безкоштовні. Картка не потрібна.

← НазадНаступний урок →

Отримуй одну пораду з Python чи вебу — щодня поштою

Коротко, без води, без спаму. Відписка — в один клік.