I use quite a few CSS variables, and looking at a website it looks like I’m using them for two purposes. There are probably other good reasons to use them, but I’m just telling you that’s what I use them for.
- I hate “magic numbers”, whether they’re buried in my CSS, JS, or PHP. So I’m trying to pull them from everywhere else and put them as CSS variables (and in PHP as PHP constants). So, for example, I have a good number that looks like:
--body-top-border:15px; /* Top margin size of dark border (goes away as browser shrinks) */
--button-color:#DDD; /* Color for all tab and button links */
--box-padding:3px; /* Padding for any text box */
This type of variable is used in my CSS, like:
where for the body element, I really didn’t save anything, but I extracted the magic “15px” value that would otherwise be buried in my CSS, and put it in the CSS variable block. For the article padding I used it in many places so all my boxes have the same padding and I just declare the 3px value once. There are of course other ways to do this, with a class like “.thinPadding” that could be added to each of my boxes, but I find the CSS variable quite handy for this. Also, if I’m looking at my site and decide the padding needs to be a little thicker, I can just access the CSS variable and edit it in one place.
- The second use of CSS variables is for calculated values that can be turned into a single variable, to make my life easier. I don’t use it as much as the first use, but as an example:
--default-box-content:calc(var(--box-size) - 2 * var(--box-padding));
This would allow me to set another CSS value like this, without having to remember the details of what that box looks like:
I hope these examples help you.