Reusable Components and CSS Variables
♻️

Reusable Components and CSS Variables

Tags
Css
Web Dev
Language
English
Published
December 6, 2023
Author
Ale
In a perfect theoretical world, our components should look the same everywhere. Still, the truth is our apps are in constant development, and as such redesigns are bound to happen and requirements will change in the lifetime of our components, resulting in several versions being deployed across our app.
So how can we offer variability without shipping additional JS or maintaining several component versions?

CSS Variables to the rescue.

CSS variables are a neat way to offer flexible design opportunities without sacrificing performance or integrity. We can easily declare them with a fallback having 0 impacts on our already deployed components while opening endless customization opportunities.
 
element { padding: var(--my-spacing-1, 1rem); }
 
Another amazing CSS variable feature is inheritance, this feature allows us to define the values in the parent and be inherited by all the childs, so we just need to declare all the values in the parent container and everything would be inherited by all the instances of the variable inside it.
 
.parent { --my-spacing-1: 20px; .child { padding: var(--my-spacing-1, 1rem); } }

With great power comes great responsibility

With this much flexibility, we sacrifice control over our components and as such without proper supervision, we can end with too many visual inconsistencies. This isn’t an issue if your development process includes visual validations and UX/UI testing for changes.
The other important consideration is inheritance, because of this we need to be extra mindful of our naming conventions to avoid overlapping, so one of the first steps before implementing CSS variables is defining a good naming strategy. As a side note here, inheritance can be controlled with the @property declaration, currently only supported in Chromium-based browsers, but support is coming soon to Firefox in version 123 (expected to release in Feb 2024)
@property --my-css-variable { syntax: "<length>"; // controls de accepted value types inherits: false; // toggles inheritance initial-value: 50px; // fallback value if not declared }
 
Further reading: