3

I have an element in which I need to add 10 pixels (10px) to a percentage (100%). I'm using the built CSS calc() function which should do the trick, however it seems to be causing a problem when used in conjunction with LESS CSS.

I have looked at this answer and it doesn't fix the issue. I couldn't find a scenario where anyone uses a plus symbol so I can't find an answer anywhere. The only examples are of minus symbols by used instead which is not what I need.

This is my code:

.element { width: ~"calc(100% + 10px)"; }

Which is output as:

.element { width: calc(100%+10px); }

In Chrome...

Width attribute in Chrome browser

The reason it doesn't work is because it needs spaces around the plus symbol. How can I get this to work? There doesn't seem to be a way to retain the spaces.

Community
  • 1
  • 1
  • you can try escaping the `+` symbol: `width: calc(100% ~"+" 10px);` – Pete Feb 21 '17 at 11:35
  • I tried that but it outputs the escaping characters as well for some reason. –  Feb 21 '17 at 11:43
  • Are you sure your less is being processed correctly - seems to work here: http://codepen.io/anon/pen/JEgywW – Pete Feb 21 '17 at 11:47

1 Answers1

4

You can escape the calc arguments in order to prevent them from being evaluated on compilation.

Using your example, you would simply surround the arguments, like this:

calc(~'100% + 10px')

LESS CODE

div {
   > span {
    width:calc(~'100% + 10px');
    }
 }

CSS OUTPUT

div > span
{
  width: calc(100% + 10px);
}

Inspect element image given below

enter image description here

Prasath V
  • 1,336
  • 4
  • 20
  • 39
  • I'm confused, your code example uses a minus symbol but your image example has a plus symbol? I tried your suggestion but it doesn't work. It's fine for minus but for plus it removes the spaces. –  Feb 21 '17 at 11:39
  • I think it might be a bug in LESS. Using your exact code above doesn't work with + but does with -. In the escape for the + symbol it must be doing something extra that's removing the spaces somehow. –  Feb 21 '17 at 11:43
  • in case you need to mix Less math with escaped strings: `width: calc(~"100% - 15rem +" (10px+5px) ~"+ 2em");` . Compiles to: `width: calc(100% - 15rem + 15px + 2em);` – Prasath V Feb 21 '17 at 11:48
  • Ugh. It looks like the LESS compiler I was using is out of date and has a bug in it relating to plus symbols. Using LESS installed via NPM seems to do the trick. Thanks for the help and sorry to waste your time. –  Feb 21 '17 at 12:04
  • No problem.. Happy to help.. :) – Prasath V Feb 21 '17 at 12:17