iEFdev

Code, Computers & Random Junk

Using Variables in CSS

With preprocessors like SASS and LESS you can use variables in CSS, but you can also do that with the default/built-in: CSS Variables (Custom Properties). The browser support is about 66-67%. It’s basically only IE*/Edge, Opera mini and Blackberry that doesn’t support this. Meaning - if you care about browser support you would find another solution.

With CSS variables you could reduce the number of media queries, defining all the properties and then use them throughout the code. Setting upp 3 queries with different width for example. That will give much cleaner files/code.

CC Variables (Custom Properties)

Basic example:

:root {
    --foo: green;
}


div.fooBar {
    color: var(--foo);
}

The color is set to green in div.fooBar.

With media queries

So, to reduce the number of queries, one could maybe do something like this:

Css:

/* Default values */
:root {
    --bgnd: whitesmoke;
    --txt: #333;
}

@media (min-width: 600px) {
    :root {
        --bgnd: wheat;
        --txt: #111;
    }
}

@media (min-width: 768px) {
    :root {
        --bgnd: #030;
        --txt: whitesmoke;
    }
}

@media (min-width: 1024px) {
    :root {
        --bgnd: whitesmoke;
        --txt: #333;
    }
}


div.fooBar {
    background: var(--bgnd);
    color: var(--txt);
}


/* rest of the CSS file */

Html:

<div class="fooBar">
    <p>Lorem Ipsum etc&hellip;</p>
</div>

As you see, it’s just a dummy example, but you get the picture. And it’s just to add more to each block and then doesn’t need to interrupt the code with (more) queries. They stay on top.

You can also add fallback values, like:

div.foo {
    color: var(--txt, black);
}

I expect the code to be much cleaner when you can put it up like this way, or simular. Just to fill up the queries with all values and yo can edit one value to change the rest. That’s really nice when you test out new colors for your site for example.


There are a couple of good posts to read more about this, with more examples. How to use it with javascript, fallback values.

To check on updates of browser support - visit Caniuse.


It would be really nice if Microsoft could add this. Then at least all major (desktop) browers would support it. I’m going to use it when I create/test sites here, but perhaps not Live. But, there’s a lot of potentials using this. I can see the benefits, when doing “font stacks”, using it with calc() and other functions.

If there was full support for this I would definitely use this over preprossecors. Anything bundled is always to prefer.


Happy hacking…

/Eric

Comments