Discover how CSS variables (custom properties) can streamline theming in web development, with real-world tips and code examples.
Table of content
Theming is essential for creating flexible and maintainable web designs. With CSS variables (also known as custom properties), developers can easily swap color schemes, tweak spacing, and configure style properties with minimal code. This article explores how CSS variables revolutionize theming for modern web development.
CSS variables are custom property values defined in your stylesheet. Unlike preprocessor variables ($color
in Sass, for instance), CSS variables are dynamic and inherited through the DOM, making them highly useful for responsive theming and design systems.
:root {
--primary-color: #1200ee;
--secondary-color: #ffa000;
--font-size-base: 16px;
}
Start by declaring your theme values in the :root
selector. This sets the variables globally.
:root {
--bg-color: #ffffff;
--text-color: #222222;
--accent-color: #00c6ae;
}
Reference variables using the var()
function:
body {
background: var(--bg-color);
color: var(--text-color);
}
a {
color: var(--accent-color);
}
One of the greatest benefits is the ease of changing themes. For example, to enable a dark mode, override the base values with a class:
.theme-dark {
--bg-color: #1d2331;
--text-color: #f8f8f8;
--accent-color: #f34b7d;
}
Add or remove the theme-dark
class to your <body>
element to switch themes instantly.
Variables can be updated within media queries for responsive design:
@media (max-width: 600px) {
:root {
--font-size-base: 14px;
}
}
Localize variables for components or UI elements:
.btn-primary {
--btn-bg: var(--accent-color);
background: var(--btn-bg);
color: #fff;
}
color: var(--missing, #333);
CSS variables make theming scalable and intuitive, especially for dynamic or design-driven web projects. Try integrating them into your next project for easier maintenance and more creative flexibility!