Last Updated: July 27, 2016
·
6.475K
· amoniker

CSS does Math

For some layouts, a little-known CSS function called calc() can be quite useful. Calc allows you carry out four basic mathematical operations ( + - * / ) using any combination of css units.

It's easy to use too:

#element {
    width: calc(100% - 50px);
}

This is particularly effective when you'd like to offset a dynamic-width element by the fixed-width of a neighbor.

For example, imagine you have something like this:

/¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\
| /¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\ |
| |                    | |
| |      textarea      | |
| |                    | |
| \____________________/ |
|                        |
|        /¯¯¯¯¯¯¯¯¯¯¯¯¯\ |
| label: |    input    | |
|        \_____________/ |
\________________________/

And you'd like it to be responsive, like this:

/¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\
| /¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\ |
| |                                                 | |
| |                    textarea                     | |
| |                                                 | |
| \_________________________________________________/ |
|                                                     |
|        /¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\ |
| label: |                  input                   | |
|        \__________________________________________/ |
\_____________________________________________________/

By using CSS calc() you can achieve this with minimal effort. Give the label a fixed-width (say 90px), then set the input element's width to calc(100% - 90px).

<a href="http://jim.greenle.af/examples/css-calc" target="_blank">See Calc in action</a>

It's worth noting that calc() isn't completely standardized yet, so until then you should use the prefixed versions.

#element {
    width: -webkit-calc(100% - 3em);
    width:    -moz-calc(100% - 3em);
    width:         calc(100% - 3em);
}

It's also important to note that it won't work in Opera, Android, or Blackberry. It does work in IE9, but not in IE8. So make sure to provide appropriate fallbacks! See the full <a href="http://caniuse.com/#feat=calc" target="_blank">compatibility table</a> for more.

What other tricks can you do with calc()?

5 Responses
Add your response

Nice protip. You should add which browsers are supported. http://caniuse.com/#feat=calc

over 1 year ago ·

just to save some time, wont work on ie8... nice feature though...

over 1 year ago ·

@paranoida Thanks. Updated with compatibility details!

over 1 year ago ·

@fredylg What does work in IE8? ;)

over 1 year ago ·

Nice. just wish ie wouldn't always have to be a party pooper... but hey, you can set a different width for ie like
.box{
width: 90%; /* fallback for browsers without support for calc() */
width: calc(100% - 80px);
}

over 1 year ago ·