Implementing light and dark mode on the web
practical theming with CSS.
CSS custom properties for color tokens, a data-theme attribute toggle, and prefers-color-scheme as default.
hardcoding two full stylesheets or only relying on JS to recolor.
WHAT THIS TESTS This checks fluency with CSS custom properties and the platform features built for theming. Dark mode is table stakes, and the clean solution is a single set of variables, not duplicated styles.
A GOOD ANSWER COVERS Define your semantic colors as CSS custom properties on :root, for example a background, surface, and text token. Provide a dark override by redefining those same properties under a scoping selector such as html[data-theme=dark] or a .dark class. Components reference only the variables, so flipping the attribute instantly recolors everything without touching component CSS. Use the prefers-color-scheme media query to pick a sensible default from the user's OS setting, and a small script to let users override and persist their choice in localStorage. Add the color-scheme property so the browser styles native widgets, scrollbars, and form controls to match.
COMMON WRONG ANSWERS Writing two complete stylesheets and swapping the href, which doubles maintenance and causes flashes. Using JavaScript to walk the DOM and recolor elements, which is slow and brittle. Forgetting color-scheme, leaving native controls and scrollbars stuck in light mode.
LIKELY FOLLOW-UPS How do you avoid a flash of the wrong theme on load? How do you respect the OS setting but still allow a manual override? How do you test contrast in both modes?
ONE CONCRETE EXAMPLE On :root you set --bg: white and --text: #111. Under html[data-theme=dark] you set --bg: #111 and --text: #eee, and add color-scheme: dark there. A toggle button writes data-theme to the html element and saves it to localStorage; an inline script reads it before paint. Every component just uses var(--bg) and var(--text), so the whole UI flips with one attribute change.
Read the original → developer.mozilla.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.