CSS custom properties let you define values like colors once and reuse them. Changing the variable changes all uses, making theme switching easy.
Custom properties must start with -- and be inside a selector like :root. The correct syntax is :root { --bg-color: #121212; }.
:root {
--bg-color: white;
}
[data-theme="dark"] {
--bg-color: black;
}
body {
background-color: var(--bg-color);
}The :root defines --bg-color as white by default. The dark theme only applies if data-theme="dark" is set. Without it, background is white.
The attribute selector html[data-theme="dark"] p targets paragraphs inside when data-theme is dark. Other options look for the attribute on paragraphs or use a class not set.
Accessibility guidelines recommend a minimum contrast ratio between text and background. Using a contrast checker tool helps pick colors that meet these standards.
