In our previous posts on CSS Pre-processors, we have discussed how we can calculate length with their special functions. To tell the truth, we can also do similar things in CSS3 with the new function named
calc(). In this post, we will see how to utilize this function in the stylesheet.
Using calc() function
As mentioned above, we can use
calc() to determine lengths like
font-size, etc. To measure, we can use Mathematical expressions: Addition, Subtraction, Division and Multiplication.
For an example, let’s say, we have three
<div> within a wrapper, as shown below.
calc() function, we can easily set these
<div> into columns with equal width this way.
The following Mathematical operation
calc(100% / 3); divides 100% of the parent width by three and here is how it turns out in the browsers. The three
<div> are having equal width.
Follow the link below to see it in action.
Additionally, Kurt Maine also shown how
calc() function is really useful for creating responsive layout.
A few things to note
There are a few things worth noting when using
- First, the calculation is conducted from left to right.
- Division or Multiplication will be calculated first and Math expressions inside parentheses will also be calculated first.
calc()is currently not supported in Opera.
-webkit-, is needed to cover earlier Firefox and Chrome versions.
- We can use different units for the Operation, for example calc(50% – 10px)
-signs have to be separated with whitespaces, for example
calc(100% -5px)will return invalid, as it is only interpreted as percentage followed by negative value. But, whitespaces are not needed for
Prior to CSS3 and CSS Pre-processor, we are limited to fixed type of length. Today, with
calc() function we are able to set length in a smarter way and below are a few references to dig into this function further.
- calc() documentation – W3.org
- CSS3 Gems, The calc() function – Site Point
- calc() function browsers compatibility – caniuse.com
Have you tried using this function in your latest website?