This post on CSS calc() on HTML5Rocks got me thinking about how I could use calc() and have it work cross browser. Calc() will be a valuable feature in CSS3 once it is supported. The biggest thing it allows you to do is mix percentage and absolute values as well as mix sizing units.
The biggest problem with calc() right now is that it is not well supported. Firefox supports it with the ‘-moz-‘ prefix, and Chrome will add support in version 19 with the ‘-webkit-‘ prefix. IE9 has support for it, un-prefixed. Because of the vendor prefixes, I’m guessing for now, cross browser syntax would look something like this.
width: -webkit-calc(50% - 100px);
width: -moz-calc(50% - 100px);
width: calc(50% - 100px);
In the above example, I provided a fallback for older browsers first, followed by the 2 vendor prefixed versions and finally the un-prefixed version. See the gist here.
While thinking about using calc(), I wondered if Modernizr had a test for it. I was sure it must but discovered that it did not. While it looked like someone tried to add a test, it was missed. So I contacted Paul Irish and asked him about it, and he worked with the original developer to add the test. You can now run the test in Modernizr to see if it is supported and write different CSS rules based on that. But you still need to provide and fallback and use the vendor prefixes.
It also got me wondering about how calc() would work in a language like Sass. I’m assuming you would just write it out and it would work, but since Sass has it’s own method for doing calculations, it’s worth exercising caution.
I can’t wait until we are able to use calc() to calculate values in CSS. It’s the first step to being able to use something like Sass in the browser. But until it is well supported, it requires you to write multiple rules. If you are opposed to that, you should stick with Sass or Less which do the calculations and conversion for you.