Sub topic 1
How Dark Mode Works on the Web
Prerequisites
Assume you know basic HTML and CSS selectors, the cascade, CSS color values, and basic JavaScript DOM operations. You should understand that a media query applies styles only when its condition is true.
How dark mode works on the web
Dark mode is a color theme with a darker background and lighter foreground content. A web page can choose the theme from the user’s operating system setting. The browser exposes that setting to CSS, so the page does not need to detect the operating system directly.
A useful dark-mode design separates color decisions from component styles:
| Part | Responsibility |
|---|---|
| Theme condition | Selects light or dark mode |
| Color tokens | Stores reusable theme colors |
| Component rules | Uses the tokens for backgrounds, text, and links |
Following the system setting with prefers-color-scheme
The prefers-color-scheme media query checks the user’s preferred color scheme. Its value is usually light or dark. When the operating system is set to dark, the browser applies rules inside the dark query.
:root {
--bg: #ffffff;
--text: #1a1a1a;
--link: #0b5fff;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #121212;
--text: #e6e6e6;
--link: #8ab4ff;
}
}
body {
background: var(--bg);
color: var(--text);
}
a {
color: var(--link);
}The browser evaluates the media query when it loads the page. It can also update the result when the user changes the system setting. This automatic approach respects the user’s existing preference, but it does not provide a manual choice by itself.
Storing colors in custom properties
A CSS custom property is a reusable value whose name starts with two hyphens. Defining semantic tokens such as --bg and --text keeps components independent from specific hex values. Override the tokens once per theme, then use var() throughout the stylesheet.
This structure makes later changes safer. You can adjust the palette without searching every component for individual color values.
Exercise
What changes when the system switches from light to dark?
Show answer
The prefers-color-scheme query matches, the dark token values override the defaults, and rules using var() display the dark colors.