A Look Into: Using CSS Variables
Variables, officially known as Custom Properties, have finally come to CSS – the language we use daily for styling webpages. We have discussed using variables with CSS Pre-processors in our previous posts. Today, we will see how to use them natively in CSS.
Declaring Variables
CSS custom properties are defined using a name that begins with two dashes (--
), like so:
--primary-color: #333;
In the example above, we created a custom property named --primary-color
. Unlike some CSS Pre-processor variables, custom properties must be declared within a CSS ruleset, typically on the :root
pseudo-class to make them globally available.
For example:
:root { --primary-color: #333; }
When naming custom properties, it’s advisable to follow standard CSS naming conventions.
CSS typically uses dashes to separate words (kebab-case), like --primary-color
. While JavaScript often uses camelCase (e.g., variableNamesLikeThis
), sticking to kebab-case for CSS variables ensures consistency within your stylesheets.
Using Variables
How do we apply these variables in CSS rules? We use the var()
function to retrieve the value of a custom property. For instance, to apply the primary color to the body’s background, we would write:
:root { --primary-color: #333; } body { background-color: var(--primary-color); }
CSS variables (Custom Properties) are now widely supported across all modern browsers without vendor prefixes.
Scope
If you are familiar with JavaScript, you should already understand the concept of Scope. Similarly, scope applies to CSS custom properties. The value is inherited and will be applied to the element where it is declared and its descendants.
In our previous example, declaring the variable on the :root
pseudo-class makes it available globally to all elements on the page.
If we declare it within a specific selector, like a div
:
div { --primary-color: #333; /* Or a different value */ }
Then the variable (or its specific value within this scope) will only be available to that <div>
and its descendants.
Further Resource
Conclusion
Without a doubt, CSS Custom Properties (Variables) are a powerful addition to CSS. They are now a W3C Recommendation and widely supported, making them a standard feature for managing styles directly in CSS. This often reduces the need for pre-processors for tasks like theme management or maintaining consistent values.
Visit the demo page to see CSS variables in action.