Use CSS Variable in React Projects

In this article I am going to tell you a way in which you can declare variable in one CSS file and use it all over your project.

Why is this useful? Consider a situation where you want to change background color of all your pages, then it will be tedious task to replace the color in every css file. Instead of this if we assign background color to a variable and then simply change the value of our variable our task will be done. Sounds easy, doesn't it?

How Can we do this? We can add variables in the index.css file and then call them in other CSS files.

index.css file

*{
   margin: 0;
}
:root {
    --bgColor: #1e2832;
    --headingColor: #a166ff;
    --fontSize: 20px;
    --marginSize: 15px;
}

Now lets say you have a file named Landing.css then you can access the CSS variables as give below

.IntroTitle{
    color:  var(--headingColor);
    font-size: var(--fontSize);
    margin: calc(0.5 * var(--marginSize));
    font-weight: bold;
}
  • Here we declare the variable under the :root and custom variable always start with --
  • We can access a variable using var(Variable_Name)
  • If we want to modify the variable value for that property only we can use calc()

Thank you for reading this and hope it helps.