CSS layout gets smarter with calc()

Alex Danilo

Creating a nice CSS layout starts with assigning sizes for all the things being placed in a web application. One highly requested feature has always been the ability to specify sizes using a mixture of sizing units. For example, it’d be nice to be able to reserve 50% of an area plus a fixed amount of space, say 10px. Well you can do that right now using the calc() property. You can use this feature anywhere a length or number is used, so you can use it for positioning things, or in rgb() color values as well, so it has lots of great uses in a style sheet.

What you can do with calc()?

The calc() property can be used anywhere there’s a CSS length or number in your stylesheet.

It gives you two main features to make layout more flexible:

  • Mixing percentages and absolute values.
  • Mixing sizing units.

Mixing percentages with absolute units

Let’s take a look at an example of mixing percentages with absolute units. Say we’d like to allocate 50% of the available area less a fixed amount of pixels, then we could write it as so:

#foo {
    width: calc(50% - 100px);
}
<div id="foo">Always 100 pixels less than half the available area</div>

If it had a background color of green it’d look like:

and if you shrunk the parent size, it would look like:

The nice thing here is we always know the right hand edge of the content will be 100px to the left of the middle of the containing area. Being able to combine different value types this way allows your web application to handle layout on different size devices with far greater control than before.

Mixing units

Another great thing is the ability to combine units with different measurements to get a resulting size. For example you could set sizes relative to the current font size by mixing 'em' and 'px' units.

#bar {
    height: calc(10em + 3px);
}

You can find some great examples of combining values here and here.

Try it out

With calc() you can use +, -, * and / to add, subtract, multiply and divide values, allowing all sorts of possibilities. You can use calc() anywhere a CSS length or number can be used. We’re also working on adding calc() for angle and frequency properties soon. The calc() property for lengths is available now in Chrome 19 (Dev channel build) by use of the -webkit-calc property, in Firefox since version 8 using the -moz-calc property and in Internet Explorer since version 9 unprefixed. Let us know what you think by leaving a comment below.