CSS custom properties and variables are slowly gaining popularity now that they’re beginning to be supported on more major browsers. Custom properties and variables are a great new way to make the CSS language more flexible and dynamic, and best of all, they’re simple to use and work with, and if you’re a practiced CSS developer, you should have no problem adjusting to using them (it also might help if you have a tiny bit of JavaScript or jQuery knowledge — though this isn’t necessary at all!).
To start using CSS variables, you’ll need to first create some custom properties. Custom properties are author chosen properties that can be named anything and assigned to any HTML element to use later as a variable. Custom properties always begin with two dashes, like this: –header-color, or –text-color. You can use any name you want, and you can assign them to any property you want, though your desired effect won’t apply to any HTML elements unless you call the variable within another property (more on that later). Check out the example below to see how to easily create your own custom properties:
div{ --text-color: #5b63fe; }
So how do we use these custom properties? That’s where the variables come in. Let’s say we want to use our new custom –text-color property to apply to all the text in every p element. You would be able to do that by calling the var() function and passing your desired custom property through that function, assigning it to the property that you’d like the variable to be applied to (so in this case, we want to set the color property to #5b63fe). See below for an example of just how that would look:
p{ color: var(--text-color); }
That’s it! You can now apply the –text-color variable to any property you’d like (assign it to background colors, links, etc), it doesn’t have to be applied exclusively to text just because that’s what we’ve called it (remember, you can call it whatever you want). CSS variables are actually incredibly simple and straightforward to use. Try them out on your next project!