11

I'm trying to use css varible in my Angular application, inside a child component, and it's just not working. In the browser's Elements tool (I'm using Chrome latest version) the var() doesn't do anything. expamle:

css file:

:root {
  --width: 43.75%;
}

#content {
  display: grid;
  grid-template-columns: repeat(2, var(--width));
  grid-auto-rows: 90%;
  grid-gap: 3px;
  align-content: center;
  justify-content: center;
  border: 2px solid black;
  width: 400px;
  height: 250px;
  margin: 0 auto;
}

And thats how it's shown in the browser: enter image description here

Is CSS Variables can work with Angulat at all? Thank you

TalGabay
  • 238
  • 2
  • 9

3 Answers3

21

Your root selector probably gets also attribute with angular component id.

Try this

::ng-deep :root {
  --width: 43.75%;
}
Vlad S.
  • 396
  • 1
  • 8
  • 1
    Thank you! it works now. probably wrong root selector – TalGabay Jan 23 '18 at 08:50
  • 1
    after styles encapsulating your selector will be smth like this `:root[_ngcontent_c7] {...}`. The `::ng-deep` removes styles encapsulating for next selectors. – Vlad S. Jan 23 '18 at 09:23
  • 3
    ::ng-deep is being deprecated. "The shadow-piercing descendant combinator is deprecated and support is being removed from major browsers and tools. As such we plan to drop support in Angular (for all 3 of /deep/, >>> and ::ng-deep). Until then ::ng-deep should be preferred for a broader compatibility with the tools." [Link](https://angular.io/guide/component-styles#deprecated-deep--and-ng-deep) – Srikanth May 03 '18 at 06:00
12

I know this is old, but a better solution than ::ng-deep is to use :host instead. This will avoid issues later on when ::ng-deep is deprecated.

:host {
  --width: 43.75%;
}
J Hutch
  • 121
  • 1
  • 2
1

CSS variables don't depend on Angular, they rely on your browser. You need to have an up-to-date browser to use them. CanIUse can help you with that.

Since you're using Angular, you could use .scss files, or .less files, for SASS and LESS. They both handle variables, and much, much more.

If you're using the CLI, simply rename your files, and rename the reference to those files in your components decorators.

You can also go to .angular-cli.json and change the value of styleExts to the one you chose.