Using calc & var with Microsoft’s Ajax Minifier

Ji Pattison-Smith
2 min readJan 15, 2021

--

CSS variables are great (go and read about them if you haven’t used them yet). But they’re pretty new. And that means if your application depends on an older tool like Microsoft’s AjaxMin (last updated in 2015) to minify your CSS, you might hit this roadblock.

Here’s some (not very creative) CSS which uses variables:

body {
--some-padding: 10px;
--some-more-padding: 20px;
}
.padded-box {
padding: var(--some-padding);
}
.extra-padded-box {
padding: calc(var(--some-padding) + var(--some-more-padding));
}

Should be pretty obvious what’s going on there — we’re setting up some variables, and adding them together. Easy peasy. But minified we get this:

body{--some-padding:10px;--some-more-padding:20px}.padded-box{padding:var(--some-padding)}.extra-padded-box{padding:calc(var(--some-padding)+ var(--some-more-padding))}

See the problem? It’s subtle. I’ll give you a minute.

I’ll forgive you if you didn’t spot it. There’s no space before the + sign. That makes the whole statement invalid, so you won’t get any of that sweet, sweet padding. Don’t believe me? Here’s what the spec says:

…white space is required on both sides of the + and - operators. (The * and / operaters [sic] can be used without white space around them.)

Why AjaxMin feels the need to remove the preceding space while leaving the succeeding one in-tact I can’t tell you. But what I can offer is a nifty little solution — multiply the preceding var by 1. Just like this:

body {
--some-padding: 10px;
--some-more-padding: 20px;
}
.padded-box {
padding: var(--some-padding);
}
.extra-padded-box {
padding: calc(var(--some-padding)*1 + var(--some-more-padding));
}

Now the minifier gives us output that browser is happy to use. The space around the + is preserved, as is the space around our box.

And because 1 is “the identity element for the multiplication of real numbers” (i.e., you times something by 1 you get the same something), the final styling is just as if we didn’t do it.

It might be nifty (if I do say so myself), but it’s a hack. If you can, use something more up to date than AjaxMin. But if that’s not an option, I hope this’ll save you a headache.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response