More CSS Magic: Using CSS Custom Properties

  • Post author:
  • Post category:Web Design

So, relatively recently I wrote a post praising the CSS Grid system of styling websites and web applications. From the ease of implementation and use, to the fact that you have minute control over each element of your site, while still having a seamless transition from mobile to desktop, Grid is something I still recommend highly today.

CSS Grid has been widely supported for a few years at this point, so I was obviously under a rock for a while before I discovered just how useful it was. Coming back out from under that same rock, I’ve recently discovered CSS Custom Properties, or CSS Variables.

The logo for CSS3CSS Variables are something that makes the job of developing user interfaces and web pages even more modular, arguably easier, and all over much more elegant. I’ve been itching to have access to variables in CSS since I started my position as a UI/UX Developer.

CSS Variables only recently (within the last 1-2 years) became widely understood by all browsers, so it’s reasonable that we haven’t been using this specific method before. But even before discovering CSS Variables, I knew that a solution to modularity in my stylesheets existed in preprocessed CSS languages like SASS and SCSS.

Unfortunately, using a preprocessor means that we need to ask the server and/or the client to do additional work in order to render a webpage—which is something that could have slowed down our sites, and added another potential layer for error when it comes to creating and hosting our client’s webpages. Because of the potential risk, these solutions weren’t able to be used for our purposes.

CSS variables are declared very similarly to browser-specific rules such as -webkit or -moz, with the difference being that you declare them beginning with two hyphens, like this: --my-super-cool-variable: 14px;

Using CSS variables adds a ton of different possibilities for creating beautiful web applications and sites. But in order to understand CSS variables, first, we need to discuss the idea of scope.

The scope of CSS variables is very similar to that of JavaScript. You can declare “global” variables by putting them on the :root pseudo element. Using this pseudo element, the rules will be accessible by basically everything in your stylesheet (or, honestly, the entire website).

:root {
	--my-super-cool-color: #ff9405;
}

In order to use scope modularly, you can also apply CSS Variable rules to the elements within your sheet. Generally, this is good for styling individual elements, widgets, or anything that needs a direct variation on the normal rules. You do this exactly the same way, except not on a pseudo element:

:root {
	--my-super-cool-color: #ff9405;	
}
div {
	--my-super-cool-color: #ff0000;
}

This code will overwrite the --my-super-cool-color for the <div> elements, and their children in your DOM structure. This is super useful for creating and styling specific blocks, widgets, or whatever else on your website that has the same general styles, but maybe a different color for the header, body block, or even a different font. The other great thing that applies to the general use of CSS Variables is that with one change in your sheet, you can modify this style for every element that’s using the variable. This means no more grep, or find-and-replace when altering your sheets, which eliminates a ton of errors and troubleshooting when you invariably replace color: #fff; on your site, and it also replaces background-{color: #...} declarations.

An example CSS sheet using CSS variables This is the most basic implementation of CSS Variables – apply all of them to the :root element and cascading them down.

So now that we can declare our variable—how do we apply them to our stylesheet? Well, as I mentioned before, these CSS Variables operate a lot like JavaScript, and to invoke them, you just need to put them inside of the var() function right inside of your CSS document:

div {
	color: var(--my-super-cool-color);
}

Notice how the var() function is on the properties value, and not the property itself. CSS Variables cannot (currently) be used to declare the property itself, and as such, you should never have code that looks like:

div {
	--my-variable: color;
	var(--my-variable): #fff;
}

And, as with standard CSS, in order to do mathematical calculations, you need to use the calc() function:

div {
	--standard-margin: calc(20px * 2); /* correct usage */
	--substandard-margin: 20px * 2; /* won't work */
}

And, on a similar note, CSS variables don’t need to be actual valid CSS values, but when using them, you must get them to a point where they are valid. Take this variable for example:

:root {
	--another-variable: 20;
}

This is a perfectly valid declaration, but in order to use it in a call, you might need to do a little bit of fiddling:

div {
	margin: var(--another-variable)px; 
	/* won't work, as the interpreter understands this as "20 px"
	   instead of "20px" */
	
	margin: calc(var(--another-variable) * 1px); 
	/* will work, as interpreted "20 * 1px = 20px" */
}

There are three core reasons that make up my argument for why I recommend using CSS variables in your projects going forward. The first of these reasons is in making your code more readable: this is the argument for using variables in most languages, and I think the code speaks for itself, so I won’t dive too deep into it—but having a human-readable name for value (especially one that isn’t as human-readable, like a hexadecimal color code) makes the code much easier to work with.

The second of these reasons is that you can spot errors in your CSS code much faster. It can be a huge pain to sift through a CSS document to find errors, especially if it’s a project that has been around for a long time and has been constantly built on top of (we’ve seen projects with CSS documents containing over 5000 lines of code—yikes!). Using good variable names that are easy to read and understand leads to fewer typos, and makes it much easier to spot errors if a piece of styling isn’t working how you intended.

The final reason, and what I’m going to say is the most important, is the fact that changing 1 line of code (or a handful, if you’re properly using media queries and redefining them) can change the look and feel of an entire project. Wanna change the main color of your sheet? Well, as mentioned before, instead of find-and-replacing or grepping your document, you can simply go to your :root element and change the hex code on your --my-project-main-color variable, et voilà! Your whole project was changed with one edited line of code.

CSS Variables can and should change the flow of how we’re styling websites and web applications majorly, and with additional support and development (as is true with most languages), we could be coming up on an era of styling that is increasingly more efficient, easier to understand, and overall more useful than those of olde. Besides efficiency, it also improves the troubleshooting and modification process—making the entire process much easier and less of a headache.

Are you interested in learning more about CSS variables? Looking to test them out yourself? Redesigning your website using them (possibly for different themes, or different projects)? Let the Armor Techs know today, and we’ll help you on your journey to cleaner, more efficient, and easier to read and understand code.