Introduction
The calc() function allows developers to perform mathematical calculations directly within style declarations.
Syntex and Basic Arithmetic Operations
The calc() function follows a simple syntax: calc( expression )
, where the expression represents the mathematical calculation to be performed.
The expression can include the following operations: +, -, *, /
.
.container{
width: calc(100% - 20px);
height: calc(100% / 2);
padding: calc(2rem + 10%);
font-size: calc(16px * 1.2);
}
This example shows that the calc() function is used to dynamically compute the values of various CSS properties.
Supported Units and Value Types
The calc() function supports multiple units such as px, em, rem, vw, vh, and %
. And we can also use CSS variables.
It might seem strange, but we can mix different types of units within the expression.
:root{
--header-height: 450px; /* CSS variable */
}
.container{
height: calc(100vh - var(--header-height));
width: calc(50% + 10vw);
margin: calc(2rem + 5%);
}
In this example, we can see that we can mix different units within the expression and we can also use CSS variables in the expression.
Example
We often use forms and the form input field doesn't fit the container. We can resolve this problem with the calc() function.
<style>
input {
padding: 4px;
width: 100%;
}
#form-box {
width: 50%;
border: 1px solid black;
padding: 6px;
}
</style>
<form>
<div id="form-box">
<input type="text" placeholder="Enter name" />
</div>
</form>
In the example, we can see that the input field doesn't fit the container, even though, we have set the width of the input to 100% of its parent. The calc()
function can solve this problem.
input {
padding: 4px;
width: calc( 100% - 12px );
/* box-sizing:border-box; Alternate solution */
}
In the above image, we can see that the input field fits the container perfectly. Or we can solve this problem with the box-sizing:border-box
property.
Important points to keep in mind
We must use space around the
+
and-
operator, otherwise, it won't work.p{ padding: calc(10px-2px ); /* Wrong! No space*/ padding: calc(10px - 2px ); /* Correct!*/ padding: calc(10px+-2px ); /* Wrong! No space*/ padding: calc(10px + -2px ); /* Correct!*/ }
One value must be a number type when using
*
.p{ padding: calc(2px * 10px); /*Wrong, doesn't work*/ padding: calc(2 * 10px);/*Correct,left-side value is a number*/ padding:calc(2px * 10); /*Correct,right-side value is a number */ }
With
/
operator, the right-side value must be a number.p{ padding: calc(2em / 10px); /*Wrong, doesn't work*/ padding: calc(2em / 10);/*Correct,right-side value is a number*/ padding: calc(100% / 4); /*Correct,right-side value is a number */ }
We must use 0px
instead of simply specifying 0
in the expression.
p{
padding: calc(20px - 0); /*Wrong */
padding: calc(20px - 0px); /*Correct */
}
Conclusion
The calc()
function helps to calculate style properties dynamically and it let us perform mathematical operations within style declarations.