DEV Community

Simon
Simon

Posted on • Originally published at simondoescoding.hashnode.dev on

I Just Had My Mind Blown: Variables In Vanilla CSS 🤯

Yesterday, I was having a little chat with a friend on Twitter about creating HTML templates; this is something I'd looked at doing before but I wasn't able to provide the level of customizability that I would have liked. I have been trying to aim my templates at non-technical users who may not have any knowledge of CSS or HTML. As you can imagine, it's quite difficult to change a picture or brand colours when the user has no idea what HTML or CSS is.

After chatting with my friend, I thought it'd be best to just have a very detailed .README file that explains everything that the user would need to change and how they would go about doing it. I got off on a tangent, as I usually do, and started googling things and then I stumbled across something... the holy grail! Exactly what I had been looking for! Variables in vanilla CSS! 🤯🤯🤯🤯🤯

I Found It!

image.png

I had to refresh the page a few times to make sure I wasn't getting trolled, I checked the date to make sure it wasn't April Fools Day but no, this was real! All my problems... well most of my coding problems were solved!

Here's how you do it

Enough of my life story, lets looks at how we actually implement this!

You have a psuedo-class in your CSS file and create a custom property inside that; this property can then be used throughout the CSS file.

:root {
    --primary-color: #C0B9DD;
}

.some-class {
    background-color: var(--primary-color);
}

Enter fullscreen mode Exit fullscreen mode

Here's a quick codepen I put together so you can see it working for yourselves!

https://codepen.io/Simon_9/pen/yLPGwOp

Top comments (1)

Collapse
 
roblevintennis profile image
Rob Levin

You should check out open props project