13

How to use CSS variable in global CSS file

Just check style.css file in stackblitz

https://stackblitz.com/edit/angular-themeing-y3jwrk?file=src/styles.css

2
  • You have a variable in a typescript class and you want to use that variable in CSS to change the styles? Please correct me if I am wrong. Commented Nov 15, 2018 at 9:05
  • CSS variable works inside component but i'm not able to use that in styles.css file Commented Nov 15, 2018 at 9:08

2 Answers 2

10

in the global css file, styles.css, I have this code:

import ...

:root {
    --main-color: #3f51b5;
}

it declares a css variable, "main-color"

then in the child component css file, I can use the variable directly

#component-body {
  background: var(--main-color);
}
Sign up to request clarification or add additional context in comments.

Comments

9

In the global style.css file, define custom properties in a :root selector.

Global variables in CSS will enable us to define theme variables such that multiple components can use the same.

Here you go:

app/style.css

:root {
  --primary-color: #fff;
  --background-color: #e5e5e5;
  --text-color: #2d2d2d;
}

To define a CSS custom property,prefix the property with two '--' like --text-color:#2d2d2d.

Now we can reference the variable in other CSS files.To use a custom property, use the var keyword to pass in a reference to the custom property.

app/header/header.component.css

:host {
background-color: var(--primary-color);
color: var(--text-color);
}

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.