Angular: css variables are not usable in components

Viewed 1004

Hi i am trying to use css variables to predefine colors for example.

Here is my app.component.css

:root {
  --main-bg1: rgb(26, 28, 29);
  --main-bg2: rgb(66, 77, 79);
  --main-bg3: rgb(93, 109, 112);
}

Problem is that when i use this variable in other components it wont work. For example

.some-class{
  background-color: var(--main-bg1);
}

How can i make this work in angular?

3 Answers

Add your variables to :host scope in your.component.scss file.

your.component.html

:host {
  --drawer-width: 300px;
  --drawer-height: 65px;
  --drawer-top-height: 65px;
  --drawer-top: #ffffff;
  --drawer-left: red;
  --drawer-right: #f5f5f7;
  --drawer-top-bottom: red;

  /* Usage sample of variable */
  .use-sample-in-div {
    background: var(--drawer-left);
  }
}

You can also change the values using the main styles.scss. First, add a class name to your component to be top priority.

app.component.html

<Drawer class="drawer-class"></Drawer>

styles.scss

:root .drawer-class {
  --drawer-width: 150px;
  --drawer-height: 32px;
  --drawer-top-height: 32px;
  --drawer-top: blue;
  --drawer-left: green;
  --drawer-right: purple;
  --drawer-top-bottom: pink;
}

Move this:

:root {
  --main-bg1: rgb(26, 28, 29);
  --main-bg2: rgb(66, 77, 79);
  --main-bg3: rgb(93, 109, 112);
}

to styles.css and then it will work

Demo

Put these styles into styles.css instead:

:root {
  --main-bg1: rgb(26, 28, 29);
  --main-bg2: rgb(66, 77, 79);
  --main-bg3: rgb(93, 109, 112);
}
Related