Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

:root selector is not working in the Angular component

Tags:

css

angular

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?

like image 535
Vitalii Avatar asked Jul 12 '26 14:07

Vitalii


2 Answers

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

like image 100
Ali BEN AMEUR Avatar answered Jul 15 '26 04:07

Ali BEN AMEUR


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.

like image 39
Trismuto Avatar answered Jul 15 '26 04:07

Trismuto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!