4

I have the following css:

#elementid {
  width: -webkit-calc(100% - 30px);
  width: -moz-calc(100% - 30px);
  width: -o-calc(100% - 30px);
  width: calc(100% - 30px);
}

The element renders narrower than expected . In Chrome, if I inspect the element, it shows:

width: -webkit-calc(70%);
width: -moz-calc(70%);
width: -o-calc(70%);
width: calc(70%);

So it's apparently interpreted the 'px' as % instead.

But if I enter the exact same CSS inline on the element, in Chrome dev tools:

width: calc(100% - 30px);

... then it renders as I expect.

As you can see I added spaces around the operator properly, so that's not it.

Why would the browser interpret it as "calc(70%)" when rendering the page, but not when I change the CSS inline using dev tools?

JustinP
  • 45
  • 1
  • 5
  • 2
    The real question is why Chrome is bothering with all those values in the first place. I would expect it to ignore the -moz- and -o- values at least... but then again, this *is* Chrome we're talking about. – BoltClock Aug 12 '15 at 17:09
  • 6
    [Can't reproduce](https://jsfiddle.net/voprm19w/). – Siguza Aug 12 '15 at 17:12
  • 2
    Are you using pure css? because in less you have to escape the `calc` like this: `~'calc(100% - 30px)'` – Yandy_Viera Aug 12 '15 at 17:12
  • 2
    I have a feeling this is Less problem, not CSS. – recursive Aug 12 '15 at 17:18
  • 1
    Watch out for the prefix bandit: `-o-calc` does not exist. – Terry Aug 12 '15 at 17:29
  • Chrome struck through the first 3 and only paid attention to the plain "calc" attribute @Yandy_Viera: Success! I am using LESS, and that did the trick. – JustinP Aug 12 '15 at 17:34

1 Answers1

2

Some browsers accept additional proprietary non-standard non-css syntax on top of the usual css. Less is build on top of standard css and therefore may not recognize it. You may also need to put an otherwise non-parseable value inside a variable and use it to dynamically build selector or other css part during compilation time.

Escaping allows you to use any arbitrary string as property or variable value. It can be used also to dynamically build selectors, but that feature is deprecated and replaced by different more powerful option.

Use either ~"whatever" or ~'whatever' syntax to escape property values. Anything between quotes is used as is with almost no changes. The "as is" rule has one exception: string interpolation works with the usual @{variableName} syntax.

So would be width: ~'calc(100% - 30px)';

Otherwise LESS will do the math inside the parenthesis first. There is a "Strict Math" setting for LESS to work around this.

Check this amazing answer for more information Disable LESS-CSS Overwriting calc()

Community
  • 1
  • 1
Yandy_Viera
  • 4,320
  • 4
  • 21
  • 42