Overriding CSS variables from parent component

Viewed 1531

there!

So, I'm trying to do the following: I have a small component in AngularJs that will render a tag-like unit. I am defining general styles inside it, like colors and borders. They are supposed to be the default values. However, I want to outer components to be able to override it by changing the value of the CSS variable. Here's the example:

tagLike.html

.tag-like-container {
  --tag-like-color: red;
  
  color: var(--tag-like-color);
 }
 <div class="tag-like-container">
    my tag
 </div>

And, then, the outer component will call it

outerComponent

.outer-container {
  --tag-like-color: blue;
 }
<div class="outer-container">
  <tag-like></tag-like>
</div>

However, the final value of --tag-like-color is red, but I want it to be blue. Any ideas on how to approach this?

Thanks!

2 Answers

The issue is that your are changing the color, but you've never applied the actual color value to the .outer-container. You need to specify that .outer-container should be using the variable for the color.

.outer-container {
    --tag-like-color: blue;
    color: var(--tag-like-color);
 }

found a solution! The way is to use 2 variables, like so:

outerComponent

.tag-like-override {
  --tag-like-color: blue;
 }
<tag-like class="tag-like-override"></tag-like>

And, in the innerComponent, using var(value, fallback) model, we can define

innerComponent

--final-tag-color: var(--tag-like-color, red);
color: var(--final-tag-color);

This way, if the color is defined by the outer component, the final value will be the one of the override; otherwise, it will be the fallback value, in this case, red.

By doing so, it is possible to create a manifesto of all the overridable styles on the top-most level class of the component, creating a black-box component.

Thanks for all the help!

Related