УРОК 11 ИЗ 15
Тёмная тема и CSS-переменные
2 Теория
Токены дизайна
Все цвета, отступы и радиусы держите в переменных — тогда смена темы превращается в замену нескольких значений.
:root {
--bg: #fffdf6;
--text: #131210;
--accent: #fde018;
--radius: 14px;
color-scheme: light dark;
}
@media (prefers-color-scheme: dark) {
:root { --bg: #131210; --text: #fffdf6; }
}
[data-theme="dark"] { --bg: #131210; --text: #fffdf6; }
[data-theme="light"] { --bg: #fffdf6; --text: #131210; }
body { background: var(--bg); color: var(--text); }
.btn { background: var(--accent); border-radius: var(--radius); color: #131210; }
Переключатель темы
<button id="theme">Тема</button>
<script>
const root = document.documentElement;
const saved = localStorage.getItem("theme");
if (saved) root.dataset.theme = saved;
document.getElementById("theme").onclick = () => {
const next = root.dataset.theme === "dark" ? "light" : "dark";
root.dataset.theme = next;
localStorage.setItem("theme", next);
};
</script>
Следуйте системной теме по умолчанию (prefers-color-scheme) и давайте пользователю возможность переопределить её. Проверяйте контраст в обеих темах.
