6

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?

1
  • 1
    Angular uses view encapsulation, meaning the styles in component are scoped to that particular component. But, if you define styles in your global styles.css (or .scss), they are available globally. Personally, I create variables.scss in the root of the project and declare the variables there. Then, you can use @import "src/variables.scss" in your component and use the variables defined there. You can also disable view encapsulation (as explained in docs), but I'd go against that as it can get really messy in bigger projects. Commented Jul 21, 2021 at 11:25

3 Answers 3

11

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;
}
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2

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

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.