custom properties over redefining general properties
Hey, would somebody be able to explain the benefits of choosing to lay out something like the example below with custom properties rather than redefining the general properties upon something like a state change, I've seen people recommend doing it this way.
rather than -
many thanks.
3 Replies
Custom properties just streamline your application so that if you want to change a value, you only have to change it in one place rather than hunting down every place you've used #282828 for example. Usually custom properties are defined in the root so they trickle down , defining something within a component or element is referred to as locally scoped custom properties which means it's only going to (only can be since it inherits) be used in that element and its children.
Example being you have defined your brand colours, font family, font sizes, default transition durations, anything you want within the root and then you can use those wherever you need. For instance making all your button backgrounds the brands accent colour. Then if you want to change your colours, you just have to go to the root and change it in one place instead of hunting down the rgb value or hex code everything you've used it.
An example of Using locally scoped custom props might be you have 3 cards with different tiers. Their html is nearly identical but you want different background images or different colours for each. On .card , you would define something like
then instead of having to redefine the colour, border-color and psuedo-elements background color on each you can just redefine
--_card-clr
That makes a lot of sense, thank you
You can also change CSS properties dynamically on the page which you can use to do things like select different themes. You can even do this with CSS-only techniques although you can use JavaScript as well.