About Math in CSS

This year I decided it was time to update Tyfy, my old web framework that I haven't really touched since 2021. Since then I've grown and improved as a developer and there have been many advances in front-end development. Time to put all of it to use.

For this update, I've decided to abandon SASS. While I still use it in my regular work, building and maintaining Drupal themes, I think its days are numbered. CSS has become so good, so capable in the last few years that SASS is no longer necessary. The biggest reason I still need to use it at all is that Bootstrap 5 still uses it. But for how much longer? I wonder…

The challenge for my update of Tyfy is figuring out how to replace some of the custom SASS functions I wrote. I worried that one of the more complicated functions I wrote, for calculating a grid-based line height given a font size, would be extremely difficult to replace.

And then I discovered CSS Math.

I don't know how long I've been ignorant of this, but now I know. To be fair, I already knew about calc() and min() and max() and clamp(). But the Advanced CSS Math functions blow my mind. I'm only beginning to wrap my head around how I might make use of these, but one of them has already made life so much easier.

For calculating grid-based line heights, I can use the round() function. Now, rounding is a very simple and well understood idea, but the round function has an interesting trick to it. Instead of just giving the function a value and telling it to round up or down, the function accepts a value to use as a rounding interval. I think this is very powerful. You can tell the function how to round, and you're not limited to integer values.

I can now calculate a grid-based line height for any font size just like this:

line-height: round(up, var(--font-size), var(--grid-unit));

In this example, --font-size and --grid-unit are CSS custom properties with rem unit values. The resulting line-height will be a rem value that conforms to the baseline grid established in my framework.

I am very excited by how my update project is going and I cannot wait for whatever new CSS discoveries I might make as I move away from SASS.