Question about CSS variable

what is the use of CSS variable?

So that you can store information and recall it.

One application would be if you want to use a certain padding, like 2em, and didn’t want to write it over and over again. Using the variable, if you later decide to change it to 1.8em, you would only have to change it in one place.

Can’t we use CSS class for that purpose?

I don’t think you are understanding what I am saying.

:root {
  --my-color: lightblue;
}

.main-text {
  color: var(--my-color);
}

.sub-title {
  color: var(--my-color);
}

footer {
  color: var(--my-color);
}

If I suddenly decide that I want a different color, I only need to change it in one place.

A class does allow you to change anything that has that class name at once. But in the html, you have to assign every element that class.

With variables, you can assign them within the CSS, and not have to change anything in the html.

Hope that makes sense.

I see, I guess I misunderstood. I guess he was talking about using a single class that gets used all over for that particular value. But cheryIm points out the difference. That’s not to say that you would never want to use a class to do something like that, just that this is another option that will have advantages in certain situations.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.