Last Updated: February 25, 2016
·
6.766K
· almirfilho

Calculating values in CSS3 with calc()

calc() is a new feature in CSS3 that allows us to calculate values within CSS. Is also possible to mix different value types – relative or absolute units – like px, %, em, in, cm, mm, pc, and so on (there are a bunch of new units on CSS3).

If you want to centralize a <div> for example, using the hack below is no longer needed:

#pinkfloyd {
    width: 200px;
    height: 150px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -75px; /* half of the height */
    margin-left: -100px; /* half of the width */
}

Now, with calc() you need just to do that:

#pinkfloyd {
    width: 200px;
    height: 150px;
    position: absolute;
    top: calc(50% - 75px);
    left: calc(50% - 100px);
}

Support

<br />
- IE9: fully supports it
- Google Chrome 19+ and Safari 6+: partial support with -webkit-calc()
- Mozilla Firefox 4+: partial support with -moz-calc()
- Opera: none =/

Got it? See ya!