Custom Property Theme Light Dark
Implement a theming system using CSS custom properties with light and dark variants toggled by a data attribute.
Code
:root {
--color-bg: #ffffff;
--color-fg: #1a1a1a;
--color-accent: #0066cc;
--spacing-unit: 8px;
--radius: 6px;
}
[data-theme="dark"] {
--color-bg: #1a1a1a;
--color-fg: #f0f0f0;
--color-accent: #66b3ff;
}
.card {
background: var(--color-bg);
color: var(--color-fg);
border: 1px solid var(--color-accent);
border-radius: var(--radius);
padding: calc(var(--spacing-unit) * 2);
}How the snippet works
Values that repeat across rules live in custom properties (--color-bg, --color-fg, --color-accent, --spacing-unit, --radius), so a theme change is one edit instead of a hunt through every rule.
The rules target :root — each selector names the element it restyles, in source order.
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Which elements does this stylesheet target?
- The rules bind to `:root`; when two rules tie in specificity, the one written later in the file wins.
Report a problem with this exampleOpens a pre-filled issue on GitHub.