Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular use CSS variable in global style.css file

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

like image 582
ksh Avatar asked Nov 15 '18 08:11

ksh


2 Answers

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);
}
like image 153
Henry Avatar answered Oct 23 '22 05:10

Henry


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);
}
like image 21
Himanshu Arora Avatar answered Oct 23 '22 07:10

Himanshu Arora