How to use CSS variable

CSS

4/23/2022, 2:43:23 PM

by Leo Voon

Usually CSS variable is declared globally in root scope by

:root {
    --primary: yellow;
    --bgColor: var(--primary);
}

.dark {
    --primary: black;
}
/* --bg is still yellow  */

There is time when you want to override the variable, you can move the declaration to body scope.

https://leveluptutorials.com/posts/css-variables-root-vs-body-scoping

body {
    --primary: yellow;
    --bgColor: var(--primary);
}

.dark {
    --primary: black;
}
/* --bg is now black ✅ */