11

Is there a way to use the css calc() routine using less?

If i go to http://less2css.org/ and I type the the following input (which is just a regular css rule):

width: calc(100% - 450px);

The output should be exactly the same (because it's regular css) however,

the css output which the less compiler is producing is width: calc(-350%);

Is there any way to get this working?

dippas
  • 58,591
  • 15
  • 114
  • 126
Danield
  • 121,619
  • 37
  • 226
  • 255

2 Answers2

18

Escape the value:

width: ~"calc(100% - 450px)";

Escaping is unnecessary in LESS 1.4 though, because calculations are only done when the calculation is surrounded by parentheses. For example:

prop: 20 + 10px;    ->  prop: 20 + 10px;
prop: (2 + 10px);   ->  prop: 12px;
prop: func(1 + 2);  ->  prop: func(1 + 2);
prop: func((1 + 2));->  prop: func(3);
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • +1 thanks, also, is there any way to use less variables within the expression as well or is that pushing it? – Danield Apr 30 '13 at 09:36
  • 1
    @Danield You mean `~"calc(100% - @{varname})"`? – Rob W Apr 30 '13 at 09:37
  • yes, where, varname is a less variable – Danield Apr 30 '13 at 09:40
  • @Danield Yes, the example I gave you works. It was not a question, but an answer disguised as a question ;) – Rob W Apr 30 '13 at 09:41
  • wow that's great, one last thing: what if I want to do an operation with that variable, eg: i tried ~"calc(100% - @{varname}*3) but the css output didn't calculate the *3 part – Danield Apr 30 '13 at 09:52
  • 2
    @Danield Put the calculation outside the escaped string: `@varname: @othervarname * 3;` – Rob W Apr 30 '13 at 09:53
1

If you want to do calculations within the LESS expression (apart from the actual css calc) you can quickly get yourself in a big unreadable mess like this:

 @width: 85;
 left: ~'calc('((100vw - @width) / 2)~')';

This results in :

 left: calc( 7.5vw );

I couldn't find a way to do this without the spaces being added in.

So an easier to read method is to just create an intermediate variable:

 @left: ((100vw - @width) / 2);
 left: ~'calc(@{left})';

Which results in :

left: calc(7.5vw);
Simon_Weaver
  • 140,023
  • 84
  • 646
  • 689