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 usecalc()
to determine lengths like width
, height
, margin
, padding
, 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.<div class="col one">A</div> <div class="col two">B</div> <div class="col three">C</div>With
calc()
function, we can easily set these <div>
into columns with equal width this way..wrapper .col { width: calc(100% / 3); padding: 0 10px; }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 usingcalc()
function.- 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.
- The
calc()
is currently not supported in Opera. - Prefix,
-moz-
and-webkit-
, is needed to cover earlier Firefox and Chrome versions. - We can use different units for the Operation, for example calc(50% – 10px)
+
and-
signs have to be separated with whitespaces, for examplecalc(100% -5px)
will return invalid, as it is only interpreted as percentage followed by negative value. But, whitespaces are not needed for*
and/
sign.
Final Thought
Prior to CSS3 and CSS Pre-processor, we are limited to fixed type of length. Today, withcalc()
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
Related posts:
No comments:
Post a Comment