14

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

2
  • It actually might be your browser. Commented Jan 23, 2018 at 8:03
  • You have any special postcss or similar plugins that might be killing this? Commented Jan 23, 2018 at 8:06

3 Answers 3

24

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

Try this

::ng-deep :root {
  --width: 43.75%;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! it works now. probably wrong root selector
after styles encapsulating your selector will be smth like this :root[_ngcontent_c7] {...}. The ::ng-deep removes styles encapsulating for next selectors.
::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
16

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%;
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.