How to use the CSS calc() function
Not sure what the CSS calc() function is all about? Well – read on because you’re about to learn something new.
CSS calc() is a function used for simple calculations to determine CSS property values right in CSS. The calc() function allows mathematical expressions with addition (+), subtraction (-), multiplication (*), and division (/) to be used as component values.
- The most useful feature of this function is the ability to mix units. For example, you can multiply pixels with percentage.
- What if I’m already using math functions with a preprocessor? If you’re using preprocessor math functions then it’s time to switch to native CSS math because it’s more powerful and you can simply do more things with it.
- Finally there’s a great browser support. According to “Can I Use”, this function is supported by 80.79% of browsers. On the image below you can see the browser support table.
Syntax and a few things to note
Here you can see an example of CSS calc() in action:
This is a list of a couple of things you should know about CSS calc() before you start working with it:
- Calculation is conducted from left to right.
- Division or Multiplication will be calculated first and Math expressions inside parentheses will also be calculated first.
- Prefix, -moz- and -webkit-, is needed to cover earlier Firefox, Chrome and Safari versions.
- As we’ve mentioned before, you can mix units. For example, you can multiply pixels with a percentage.
- Whitespace is required on both sides of the “+” and “–” operators. The “*” and “/” operators can be used without whitespace around them.
A selection of examples
We have prepared a few examples for you where you can see how useful calc() can be.
Example #1 – Create a simple and responsive grid
In this example you can see how to create a responsive grid. We’ve used calc() to calculate column widths for our grid.
If you want to see the HTML and CSS just click on “HTML” and “CSS” tabs above examples.
Example #2 – Centering absolute positioned elements
Don’t know how to center an element positioned absolute? It’s very easy to do with calc() – just look at our example:
See the Pen Centering Absolute Positioned Elements using CSS calc() by Alen (@alenvuletic) on CodePen.16804
Example #3 – Positioning a background image with CSS calc()
Usually we can position a background image from the top-left corner but what if we want to position it from the bottom-right corner? Here’s an example:
That’s it! If IE 8 is not very important for your project than you’ll use this calc() function very often.
We hope that you’ve learned something new from this post. It’s time for you to play around with our examples and learn more about CSS calc().