CSS calc() Function
Example
Use the calc() function to calculate
#div1
{
position:
absolute
;
left:
50
px
;
width:
calc
(
100
%
100
px
)
;
border:
1
px
solid
black
;
background-color:
yellow
;
padding:
5
px
;
text-align:
center
;
}
Try it »
Definition and usage
The calc() function is used to dynamically calculate length values.
- Note that a space is required before and after the operator, for example:
width: calc(100% - 10px); - Any length value can be calculated with the calc() function;
- The calc() function supports "+", "-", "*", and "/" operations;
- The calc() function uses standard mathematical operator precedence rules;
Supported version: CSS3
Browser support
The numbers in the table indicate the first browser version that supports the function.
The number prefixed by "webkit", "moz", or "o" indicates the first version that supports the function.
| function | |||||
|---|---|---|---|---|---|
| calc() | 26.0 | ||||
| 19.0 -webkit- | 9.0 | 16.0 | |||
| 4.0 -moz- | 7.0 | ||||
| 6.0 -webkit- | 15.0 |
CSS Syntax
calc(expression)
| Value | Description |
|---|---|
| expression | Required, a mathematical expression whose result is used as the return value. |
Automatically resize a form field to fit its container
Another use case for calc() is to ensure a form field fits the available space without overflowing its container while keeping appropriate margins.
In the following example, the form element uses 1/6 of the window's available width. Then, to keep the input element inside the form appropriately sized, we use calc() again, setting its width to its container's width minus 1em. The following
Example
input
{
padding:
2
px
;
display:
block
;
width:
calc
(
100
%
1
em
)
;
}
#formbox
{
width:
calc
(
100
%
/
6
)
;
border:
1
px
solid
black
;
padding:
4
px
;
}
Try it »
CSS Functions