I'd like to try to use css variables in my Angular 11 component.
<div class="main-content">
<a>Test Link</a>
</div>
With this app.component.css
div.main-content{
--main-color: red
}
a{
color: var(--main-color);
}
But if I try to use :root in my css link is black.
:root {
--main-color: red
}
a{
color: var(--main-color);
}
The :root selector matches the document's root element.
Why it doesn't match in my case?
UPDATE If I put :root to default styles.css in angular project that is included globally everything works.
What's wrong with my app.component.css?
You can use :host selector at component level to define css variables and it works.
:host {
--circle-size: clamp(1.5rem, 5vw, 4rem);
--spacing: clamp(0.25rem, 2vw, 0.5rem);
--main-color: red;
}
see https://angular.io/guide/component-styles for more details
You can't use the :root selector in an Angular component, it just simply won't work, neither should it. Check out https://github.com/angular/angular/issues/32177.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With