Why doesn't the CSS calc() function work for me?
I learned about the CSS function calc() and its awesome. I tried to use it like:
#abc{width:calc(100%-20px)}
But the problem with this function is that it doesn't work. I tested this code IE9 and Safari and it didn't work.
Why doesn't it work?
Solution 1:
The operator -
must be surrounded by spaces:
#abc{width:calc(100% - 20px)}
Quoting MDN info on calc()
:
Note: The
+
and-
operators must be surrounded by whitespace. For instance,calc(50% -8px)
will be parsed as a percentage followed by a negative length—an invalid expression—whilecalc(50% - 8px)
is a percentage followed by a subtraction operator and a length. Likewise,calc(8px + -50%)
is treated as a length followed by an addition operator and a negative percentage.The
*
and/
operators do not require whitespace, but adding it for consistency is both allowed and recommended.
The formal statement on this is in clause 8.1.1 of the CSS Values and Units Module Level 3 specification.
Solution 2:
All the modern browsers except Android's native browser support calc()
which makes it easier to adopt. But do note that it can have a big impact on the layout and the consequent breaking of your design on unsupported browsers.
You should use it with a fallback declaration, so it doesn't break browsers which don't support it.
width: 500px; /** older browsers **/
width: -webkit-calc(50% - 20px); /** Safari 6, Chrome 19-25 **/
width: -moz-calc(50% - 20px); /** FF 4-15 **/
width: calc(50% - 20px); /** FF 16+, IE 9+, Opera 15, Chrome 26+, Safari 7 and future other browsers **/
Solution 3:
It is supported by IE9, IE10 and Safari 6.0 (using -webkit-
prefix). You can check whole support table here: http://caniuse.com/#feat=calc