Reputation: 5421
I want to create a component and expose certain properties that could be overridden by parent elements.
I want those properties to be declared on top of the CSS class declaration so that they can be read at a quick glance, similar to how we read a function signature in programming.
Here's an example. Let's say I'm creating a button which has its own colors, but allows to change its background color if there's a --button-bg-color
defined:
.my-button {
--bg-color: blue;
/* lots of other css... */
/**
* here I assume that there might be a --button-bg-color defined,
* but I have a fallback to my own --bg-color variable
*/
background-color: var(--button-bg-color, var(--bg-color));
}
The problem with the code above is that the --button-bg-color
variable is referenced somewhere deep down the styling.
What I wish I could do is the declare somewhere up top that I might want to use this variable. This would tell me that this component expects to be overridden. But I need to declare it in such a way that doesn't set any value for the variable. This is purely about structure and intent.
Maybe something like this?
.my-button {
/* Ideally, declare variable without referencing any values */
--button-bg-color; /* no value set, but this means the propery will used later on in this class declaration */
/* Or perhaps there is something like undefined? */
--button-bg-color: undefined;
--bg-color: blue;
/* the rest of the code is the same */
}
Upvotes: 11
Views: 7591
Reputation: 548
I have found this question searching for something a bit different. I think someone might find it useful. If you really need to reset some custom property back to undefined. Here is how to do it:
.my-button {
--bg-color: var(--button-bg-color, blue);
}
.theme-1 {
--button-bg-color: red;
}
.reset-bg-color {
--button-bg-color: initial
}
So when applying just .theme-1 the button would be red, but applying both classes resets --button-bg-color back to undefined, and the fallback to blue works again.
Edit: Just found out you can use initial keyword. It seems to work the same. Original solutin was to set it to any undefind var. Ex: var(--undefined).
Upvotes: 2
Reputation: 5421
Oh well, I just realized that we can do this:
.my-button {
--bg-color: var(--button-bg-color, blue); /* inherit with fallback */
/* lots of other css... */
background-color: var(--bg-color);
}
This way there's also less repetition.
Upvotes: 9