19.0 `-webkit-` | 9.0 | 16.0
4.0 `-moz-` | 7.0
6.0 `-webkit-` | 15.0 | --- ## Code Examples ### Example 1: Dynamic Width with Fixed Margins In this example, we position a `
` absolutely, placing it `50px` from the left. We then use `calc()` to set its width to `100%` of the parent container minus `100px` to ensure it fits perfectly within the viewport without overflowing.
```css
#div1 {
position: absolute;
left: 50px;
width: calc(100% - 100px);
border: 1px solid black;
background-color: yellow;
padding: 5px;
text-align: center;
}
```
---
### Example 2: Auto-Sizing Form Fields to Fit Containers
A common use case for `calc()` is ensuring that form inputs scale nicely within their parent containers without overflowing, while still maintaining consistent padding and margins.
In the example below, the form container (`#formbox`) is dynamically sized to take up exactly 1/6th of the available container width. The `input` elements inside are styled to take up 100% of the container's width minus `1em` to prevent them from breaking out of the container's borders.
```css
/* Ensure input fields scale dynamically inside their container */
input {
padding: 2px;
display: block;
width: calc(100% - 1em);
}
/* Set the container width to exactly 1/6th of the parent width */
#formbox {
width: calc(100% / 6);
border: 1px solid black;
padding: 4px;
}
```
---
## Important Considerations
1. **Whitespace is Mandatory:**
* **Incorrect:** `width: calc(100%-10px);` (This will be treated as an invalid property value).
* **Correct:** `width: calc(100% - 10px);`
2. **Division by Zero:** Division by zero is invalid and will cause the CSS parser to treat the property declaration as invalid.
3. **Fallback Values:** For older browsers that do not support `calc()`, it is best practice to provide a static fallback value right before the `calc()` declaration:
```css
.sidebar {
width: 250px; /* Fallback for older browsers */
width: calc(20% + 50px); /* Modern browsers will override the fallback */
}
```
YouTip