DEV Community

Chuks Festus
Chuks Festus

Posted on • Originally published at Medium on

Understanding How CSS Calc() Works

The css3 calc() function is a native CSS way to perform simple mathematical operations property values. Being able to do math in code is nice and a welcome addition to a language that is fairly number heavy.

But is it useful? Well Instead of declaring, for example, static pixel values for an element’s width, we can use calc() to specify that the width be the result of the addition of two or more numeric values.

.example {
    width: calc(100px + 50px);
}

Can’t I Just Use Preprocessors?

All CSS Preprocessors do have math functions and they are pretty useful. If you have used CSS pre-processors like SASS then you must have come across something like this

.example\_\_one {
    width: 100px + 50px;
}

// Or using SASS variables
$width-one: 100px;
$width-two: 50px;
.example\_\_two {
    width: $width-one + $width-two;
}

The above example seems pretty cool however, the calc() function provides a better solution for two reasons. First is it’s ability to mix units. We can combine relative units such as percentages with absolute units such as pixels. Preprocessors can’t do that because It is something that has to happen at render time.

.foo {
    width: calc(100% - 3em);
}

In this example, the .foo element will always have a width that is 3em less than 100% of it's parent width.

Second, when doing mathematical expressions with CSS pre-processors, the value given to the browser is the resulting value of the expression.

// Value specified in SCSS
.foo {
    width: 150px + 50px;
}

// Compiled CSS and computed value in browser
.foo {
    width: 200px;
}

However, with calc() the value parsed by the browser is the actual calc() expression.

// Value specified in CSS
.foo {
    width: calc(100% - 50px);
}

// Computed value in browser
.foo {
    width: calc(100% - 50px);
}

What this means is that the values in the browser can be more dynamic, and adapt as the viewport changes. We can have an element with a height of the viewport minus an absolute value, and it will adapt as the viewport changes.

Using Calc()

The calc() function has four simple math operators: add (+), subtract (-), multiply (*), and divide (/). Basically the calc() CSS function can be used anywhere a , , ,

The calc() function can also be nested like so:

.foo {
    width: calc( 100% / calc(25px \* 8) );
}

Providing Fallbacks

For browsers that don’t support calc(), the entire property-value expression is ignored. This means that we can easily provide a fallback static value that will be used by non-supporting browsers.

.thing {   
    width: 90%; /\* fallback if needed \*/   
    width: calc(100% - 3em); 
}

Top comments (0)