DEV Community

Discussion on: What are CSS variables?

Collapse
 
jasperhorn profile image
JasperHorn

I like CSS variables a lot. As you say, though, their main disadvantage is backwards compatibility. Unfortunately, Internet Explorer is not going to get its act together, as it has been replaced and won't be developed any further. So, the 0.16% of desktop users using IE6 is just a completely lost cause, while for the 6% using another IE version, hope is running dry too.

Anyway, I have used them in two projects. For one, I decided simply not to care too much for users of older browsers. For the other, I was using so much other new(ish) technology that supporting IE didn't make sense anyway.

I like the CSS variables a lot more than the preprocessor variables that I have used. Maybe that was just the circumstances in which they used them, but there are also some nifty tricks that you can do.

For example, there was a project that generally didn't need browser prefixes in its CSS because it was rather recent. But then at one point I needed one. So, this is what I did:

.someclass
{
    --tab-size: 4;
    tab-size: var(--tab-size);
    -moz-tab-size: var(--tab-size);
}

I would never even have come up with that using preprocessor variables, because (a) they're not scoped, so you would need to add a large amount of scope to the variable name and (b) you can't keep them this close to where they matter.

The other thing that sets them apart from preprocessor variables is of course this:

p.colored
{
    color: var(--my-color);
}

.red
{
    --my-color: red;
}

.green
{
    --my-color: green; 
}

which lets you do this:

<p class="colored red">Red text</p>
<p class="colored green">Green text</p>

And even this:

<div class='red'>
  <p class='colored'>Red text</p>
  <p>Normal text</p>
  <p class='colored'>More red text</p>
</div>
<div class='green'>
  <p class='colored'>Green text</p>
</div>

Now, this example is a bit contrived and it's not something I see myself using all that regularly, but it is still really nice if you ask me.

Collapse
 
jkimexploring profile image
JkImExploring

I don't think I would have come up with doing the first example like that! That's a lot clearer than normal CSS.
It kind of is nice you can change it like that but like you said, I don't know if I'd ever use it like that. I'd probably just use a different variable.