Sub topic 2
Semantic Color Tokens for Light and Dark
Assume basic HTML and CSS, including selectors and the cascade, plus basic JavaScript for DOM attributes. The goal is to give each interface role one semantic token, then change token values instead of rewriting every component.
Semantic color tokens
A semantic color token is a CSS custom property named for its purpose, such as background or text, rather than its appearance. Components use these roles consistently.
:root {
--color-background: #ffffff;
--color-surface: #f2f4f7;
--color-text: #1a1a1a;
--color-link: #0b5fff;
}
@media (prefers-color-scheme: dark) {
:root {
--color-background: #121212;
--color-surface: #242424;
--color-text: #e6e6e6;
--color-link: #8ab4ff;
}
}
body {
background: var(--color-background);
color: var(--color-text);
}
.card {
background: var(--color-surface);
}
a {
color: var(--color-link);
}The prefers-color-scheme media query reads the operating system or browser preference. The component rules stay unchanged.
Telling the browser about your themes
The color-scheme property tells the browser which schemes the page supports. This lets built-in controls, scrollbars, and other browser UI choose suitable colors.
:root {
color-scheme: light dark;
}Use light dark when both schemes are supported. An explicit color-scheme value on the root element can later reflect a manual choice.
Writing both themes with light-dark()
The light-dark() function selects its first color in a light scheme and its second in a dark scheme.
:root {
color-scheme: light dark;
}
body {
background: light-dark(#ffffff, #121212);
color: light-dark(#1a1a1a, #e6e6e6);
}Semantic custom properties remain easier to maintain when many components share the same roles. Use light-dark() for small, local differences.
Adding a light, dark, and system toggle
A system option removes the data-theme attribute, allowing the media query to decide. Light and dark options set the attribute and persist it.
<button data-theme="light">Light</button>
<button data-theme="dark">Dark</button>
<button data-theme="system">System</button>
<script>
const root = document.documentElement;
document.querySelectorAll("[data-theme]").forEach((button) => {
button.addEventListener("click", () => {
const choice = button.dataset.theme;
if (choice === "system") {
delete root.dataset.theme;
localStorage.removeItem("theme");
} else {
root.dataset.theme = choice;
localStorage.setItem("theme", choice);
}
});
});
</script>Add selectors for root data-theme values so explicit choices override the system media query.
Exercise
Why should a component use --color-text instead of a token named --black?
Show answer
The semantic name describes the role, so its value can change for dark mode without changing the component rule.