Semantic tokens and themes
Definition and purpose
A primitive token represents a raw design choice such as a color or spacing step. A semantic token describes its role, such as surface or text. A component consumes role names so themes can change values without rewriting component rules.
Role tokens
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; font: 16px sans-serif; color: #172033; background: white; } :root { --ink: navy; --paper: white; --text: var(--ink); --surface: var(--paper); } .card { color: var(--text); background: var(--surface); } </style> </head> <body> <section class="panel"> <p id="a" class="card">Standard</p> <p id="b" class="card" data-theme="dark">Dark</p> </section> </body></html>The component consumes roles rather than palette names.
Syntax and mental model
Define primitives on :root, then map semantic tokens at the theme boundary, using an attribute like [data-theme="dark"]. If a semantic alias was computed on a parent, overriding only its primitive on a child does not change the inherited alias: re-declare the mapping in the theme scope. Keep foreground and background paired and verify contrast.
Theme override
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>CSS practice</title> <style> body { margin: 0; font: 16px sans-serif; color: #172033; background: white; } :root { --text: navy; --surface: white; } [data-theme="dark"] { --text: white; --surface: navy; } .card { color: var(--text); background: var(--surface); } </style> </head> <body> <section class="panel"> <p id="a" class="card">Standard</p> <p id="b" class="card" data-theme="dark">Dark</p> </section> </body></html>Only the dark card overrides both semantic roles.
Common mistakes
Do not name all tokens after their current colors (a dark theme might need a light text color). Theme switching is not automatic: set the attribute in HTML or application code. Do not assume tokenization guarantees accessibility.
Practice and next steps
After trying the examples, complete the linked coding exercise and review questions. Predict the result before running your code. Prerequisite: Registered custom properties. Next lesson: Logical pseudo-classes.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Semantic tokens and themes — knowledge check
Five questions on semantic tokens and themes.
Which is a semantic token name?
Where should theme-specific semantic mappings be declared?
What should change with a dark surface?
What happens if an alias inherited from a parent already resolved to navy?
What triggers an attribute-based theme rule?