An Introduction to CSS3 calc() Function

In our previous posts on CSS Pre-processors, we discussed how to calculate lengths with their special functions. Interestingly, CSS3 offers a similar capability through a powerful feature named calc(). This post explores how to effectively leverage this function within your stylesheets.

Simplifying Layouts with calc()

The calc() function allows for dynamic computation of lengths for properties like width, height, margin, padding, and font-size using basic math operations: addition, subtraction, division, and multiplication.

Consider a scenario where you have three <div> elements within a wrapper. The setup is as follows:

<div class="col one">A</div>
<div class="col two">B</div>
<div class="col three">C</div>

Using the calc() function, you can easily distribute these <div> elements into equal-width columns:

.wrapper .col {
  width: calc(100% / 3);
  padding: 0 10px;

This calc(100% / 3); operation divides the parent’s width by three, resulting in equal-width columns as displayed in browsers.

Equal Width Columns Example with CSS3 calc() Function

Check out the demonstration and source code below for a practical application.

See demo Download codes

Kurt Maine has also demonstrated the calc() function’s utility in crafting responsive layouts, highlighting its versatility.

Key Considerations for Using calc()

When incorporating the calc() function into your CSS, there are several important factors to keep in mind:

  • Calculations are performed from left to right.
  • Division and multiplication take precedence, and calculations within parentheses are executed first.
  • The calc() function is not supported in Opera.
  • For older versions of Firefox and Chrome, use the prefixes -moz- and -webkit- respectively.
  • It’s possible to mix units, such as calc(50% - 10px).
  • Spaces are required around + and - operators (e.g., calc(100% - 5px) is invalid), but not necessary for * and / operators.

Final Thoughts

Before the advent of CSS3 and CSS pre-processors, developers were confined to using fixed lengths. The introduction of the calc() function allows for more dynamic and intelligent setting of lengths. Below are some valuable resources for further exploration of this function.