The joy of calc()

Sunday, November 3, 2013

calc() is a modern css function that allows you to do basic maths in a css file. You can use it to make semi fluid layouts with great ease. This means that you can have layouts with 1 fixed width column (or more) and the rest fluid. It doesn't just stop at columns, but that is the easiest and quickest example to discuss.

The setup of calc is very simple. If we take a 2 column layout as an example, the side column always has 200px of width, the main will take up the rest, so 100% less 200px!

1/* Fixed columns */ .side { width: calc (200px); } .main { width: calc (100% - 200px); } 

The only minor issue is support , which extends to almost all browsers except Android and Opera Mini which currently have no support and Blackberry which has partial. IE9+ all have full support.

So using it responsibly just needs some simple fallbacks. There are some compromises, but these are the same as any pre calc fluid layout.

1/* Fixed columns with fallback */ .side { width: 20%; width: calc (200px); } .main { width: 80%; width: calc (100% - 200px); } 

Now any browsers that don't understand calc will use the percentage values, and the smarter browsers will over-ride the percentages with the new calc values.

The examples above are for creating a fresh design, however updating an existing layout is as simple as adding in calc() values on the next lines.

Other uses for calc() range from setting fixed gutters on a fluid layout, having fixed height headers and scrolling content within a container, setting background images a certain number of pixels from the right or bottom.

1/* Gutters */ .column { width: calc(25% - 10px); margin-right: 10px; } /* Background image at bottom right */ .container { background-position: calc(100% - 10px) calc(100% - 10px); } /* Fixed headers */ .container { height: 300px; } .container-header { height: 50px; } .container-content { height: calc(100% - 50px); } 

I'm sure there are also far more creative uses for usingcalc() however even the above are fantastically useful from day to day. I did start messing about to see if I could use nth-child and calc() but that didn't want to play ball!

1/* Code that will never work! */ .steps-for-fun:nth-child(n) { width: calc(n * 10px;); /* doubt this will ever work! */ } 

Other posts


Tagged with: