CSS calc() Function
Example
Using the calc() function to calculate the width of a <div> element:
#div1 {
position: absolute;
left: 50px;
width: calc(100% - 100px);
border: 1px solid black;
background-color: yellow;
padding: 5px;
text-align: center;
}
Definition and Usage
The calc() function is used to perform dynamic calculations for length values.
- It is important to note that spaces must be maintained around the operators, for example:
width: calc(100% - 10px)
; - Any length value can be calculated using the calc() function;
- The calc() function supports addition (+), subtraction (-), multiplication (*), and division (/) operations;
- The calc() function follows standard mathematical operator precedence rules;
Supported Version: CSS3
Browser Support
The numbers in the table specify the first browser version that fully supports the function.
Numbers prefixed with "webkit" or "moz" or "o" indicate the first version that supported the function with a prefix.
Function | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
calc() | 26.0 <br>19.0 -webkit- | 9.0 | 16.0 <br>4.0 -moz- | 7.0 <br>6.0 -webkit- | 15.0 |
CSS Syntax
calc(expression)
Value | Description |
---|---|
expression | Required. A mathematical expression whose result is used as the value. |
Automatically Adjusting Form Field Size to Fit Its Container
Another use case for calc()
is to ensure that a form field fits the available space without overflowing its container while maintaining appropriate margins.
In this example, the form element itself takes up 1/6 of the available window width. Then, to ensure that the input element within the form maintains an appropriate size, we use calc()
again to set its width to the container's width minus 1em.
Example
input {
padding: 2px;
display: block;
width: calc(100% - 1em);
}
#formbox {
width: calc(100% / 6);
border: 1px solid black;
padding: 4px;
}