CSS

CSS Variables (Custom Properties)

CSS code showing custom property definitions and usage
CSS Variables (Custom Properties)
Maintaining large CSS files used to be a headache. If you wanted a consistent color scheme, you had to do a find-and-replace for every hex code. CSS Variables (Custom Properties) changed that. You define them in a selector (usually :root for global scope) like :root { --primary-color: #3498db; }. Then you use them anywhere: color: var(--primary-color);. The beauty is that they are live. If you change the variable value with JavaScript (e.g., document.body.style.setProperty('--primary-color', '#ff0000');), every element using that variable updates immediately. This is how many dark mode toggles work. They aren't just for colors either; you can store font sizes, spacing units, or even complex calc() values. They work seamlessly with media queries, allowing you to redefine the spacing scale for different screen sizes.
2,891
Views
130
Words
1 min read
Read Time
May 2025
Published
← All Articles 📂 CSS