Academy / Advanced Level: HTML and CSS

CSS Variables (Custom Properties)

Advanced Techniques: Theming with CSS Variables

One of the most powerful use cases for CSS Variables is theming. By defining key properties like colors, fonts, and spacing as variables, you can easily switch between themes by updating the variable values.

Example: Light and Dark Themes

You can define both light and dark themes using CSS Variables, then toggle between them by changing the values.

:root {
--background-color: #ffffff;
--text-color: #000000;
}

[data-theme="dark"] {
--background-color: #2c3e50;
--text-color: #ecf0f1;
}

body {
background-color: var(--background-color);
color: var(--text-color);
}

Applying the Theme Dynamically:

You can switch themes by toggling the data-theme attribute in HTML or with JavaScript:

<button onclick="document.documentElement.setAttribute('data-theme', 'dark')">Dark Theme</button>
<button onclick="document.documentElement.setAttribute('data-theme', 'light')">Light Theme</button>

This allows users to switch between themes easily.