How to prevent Less from trying to compile CSS calc() properties?

CssCompilationLessCss Calc

Css Problem Overview


The Less compilers that I'm using (OrangeBits and dotless 1.3.0.5) are aggressively translating

body { width: calc(100% - 250px - 1.5em); }

into

body { width: calc(-151.5%); }

Which is obviously not desired. I'm wondering if there is a way to signal to the Less compiler to essentially ignore the attribute during compilation. I've searched through the Less documentation and both compilers' documentation, and I could not find anything.

Does Less or a Less compiler support this?

If not, is there a CSS extender that does?

Css Solutions


Solution 1 - Css

Less no longer evaluates expression inside calc by default since v3.00.


Original answer (Less v1.x...2.x):

Do this:

body { width: calc(~"100% - 250px - 1.5em"); }

In Less 1.4.0 we will have a strictMaths option which requires all Less calculations to be within brackets, so the calc will work "out-of-the-box". This is an option since it is a major breaking change. Early betas of 1.4.0 had this option on by default. The release version has it off by default.

Solution 2 - Css

A very common usecase of calc is take 100% width and adding some margin around the element.

One can do so with:

@someMarginVariable = 15px;

margin: @someMarginVariable;
width: calc(~"100% - "@someMarginVariable*2);
width: -moz-calc(~"100% - "@someMarginVariable*2);
width: -webkit-calc(~"100% - "@someMarginVariable*2);

Solution 3 - Css

There is several escaping options with same result:

body { width: ~"calc(100% - 250px - 1.5em)"; }
body { width: calc(~"100% - 250px - 1.5em"); }
body { width: calc(100% ~"-" 250px ~"-" 1.5em); }

Solution 4 - Css

There's a tidier way to include variables inside the escaped calc, as explained in this post: CSS3 calc() function doesn't work with Less #974

@variable: 2em;

body{ width: calc(~"100% - @{variable} * 2");}

By using the curly brackets you don't need to close and reopen the escaping quotes.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick BabcockView Question on Stackoverflow
Solution 1 - CssLuke PageView Answer on Stackoverflow
Solution 2 - CssSebastien LorberView Answer on Stackoverflow
Solution 3 - Cssicl7126View Answer on Stackoverflow
Solution 4 - CssbrohrView Answer on Stackoverflow