Keep Math in the CSS

Share this:

There is a sentiment that leaving math calculations in your CSS is a good idea that I agree with. This is for math that you could calculate at authoring time, but specifically chose not to. For instance, if you needed a 7-column float-based grid (don't ask), it's cleaner and more intuitive:

You could probably prove that the calc() takes the computer 0.0000001% longer, so explicitly defining the width is technically faster for performance reason — but that is about the equivalent of not using punctuation in sentences because it saves HTML weight.

That math can be a little more complicated as you continue. For example, like in our use cases for calc() article, what about columns in that 7-column grid that span?

Again, I'd say that's pretty readable, but it's also a good amount of repetition. This might call for using variables. We'll do it with CSS custom properties for fun. You have to pick what is worthy of a variable and what isn't. You might need fewer comments as the code becomes somewhat self-documenting:

Every single number has been given a variable in there. Too far? Maybe. It certainly makes those width declarations pretty hard to wrap your head around quickly. Ana Tudor does some serious stuff with calc(), as proof that everyone's comfort level with this stuff is different.

One of the things that made me think of all this is a recent article from James Nash — "Hardcore CSS calc()" — where he builds this:

While the solution took a heavily math-y road to get there, it ends up being only sort of medium-level calculation on the ol' complexity meter. And note that not everything gets a variable' only the most re-used bits:

This is one of the many reasons I still use Sass. You can have self-documenting variable names like this, with easier-to-read syntax ($padding vs var(—padding)), wider browser support due to less usage of calc, fewer issues with transitions due to less usage of calc, whatever minor performance benefits there may be by calculating less of it on the fly in the browser, and an overall smaller file size thanks to precompiling each of those variable names and calculations into a few characters.

calc doesn’t need to be used all the time, but I’ve had a couple instances where it really made sense. We should always do everything we can with HTML first, then everything we possibly can with CSS, then move on to things like JavaScript. Use the stack appropriately.

👋

CSS-Tricks* is created, written by, and maintained by Chris Coyier and a team of swell people. It is built on WordPress and powered up by Jetpack. It is made possible through sponsorships from products and services we like.