Introducing the calc function

Math is a necessary (if not always welcome) tool in our programming languages. We use it constantly to make all kinds of dynamic decisions.

Until recently, it wasn’t available in CSS without a pre-processor; however the introduction of the calc function to CSS3 provides a way of running Math calculations natively which increases performance and even enables mixed units.

Browser support

Unusually, in the case of the calc function browser support is actually pretty good: on the desktop it’s supported by IE9+ and the latest versions of Firefox, Safari, Opera and Chrome; on mobile it’s supported by IE Mobile, Blackberry and Safari, but not Android and Opera. -moz and -webkit prefixes are supported by older browsers.

This level of support means that provided you include a simple fallback for non-compliant browsers, you can use the calcfunction today.

How to use the calc function

Let’s start with some basic math. Imagine we have three divs and we want these divs to be a third of the width of their parent. If the HTML looks like this:

<div class="one">
Div One
</div>
<div class="two">
Div Two
</div>
<div class="three">
Div Three
</div>

Then the CSS, with the calc function would look like this:

div {
height: 400px;
width: calc(100% / 3);
}

You can see a demo of this working here. Of course, a similar effect would be possible using a simple percentage.

However, where the calc function really comes into its own is when mixing units. For example:

section {
width: calc(100% - 3em);
margin-top: calc(10% + 10px);
}

As with math calculations in most languages, we can dictate the order the equation is resolved in using parenthesis:

div {
width: calc((100% - 200px) / 3 );
}

In this case 200px will be subtracted from the 100%, and the result will then be divided by 3.

(As with math functions in other languages, division and multiplication are performed before deduction and addition; without the parenthesis in the previous example 200px would be divided by 3 and the result subtracted from 100%.)

Final thoughts

We’ve needed something like the calc function in CSS for a very long time, and its lack was one of the main reasons developers turned to pre-processors.

With steadily increasing support the calc function is likely to be one of the most widely used tools in your CSS arsenal for many years to come. Do you use the calc function in your CSS? What fallbacks do you use for older browsers? Let us know in the comments.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s