The CSS calc() function allows you to perform calculations to determine CSS property values.
- You can mix units (e.g.,
%,px,em) in a single calculation. - It is especially useful for dynamic layouts where fixed sizes and relative sizes need to combine.
🔹 Syntax:
property: calc(expression);
expressioncan include+,-,*,/.- Spaces around operators are required:
calc(100% - 50px)✅
🧩 Examples
- Responsive Width
.container {
width: calc(100% - 40px); /* full width minus 40px padding */
}
- Centering an Element with Margin
.box {
width: 300px;
margin-left: calc(50% - 150px); /* 50% of parent minus half of own width */
}
- Dynamic Font Size
h1 {
font-size: calc(16px + 1vw); /* base 16px plus viewport width */
}
- Height with Header/Footer
.main-content {
height: calc(100vh - 120px); /* viewport height minus header/footer */
}
🔹 Why calc() is Useful
- Combines relative and absolute units.
- Avoids extra wrapper elements for spacing adjustments.
- Makes layouts more flexible and responsive.
- Works in many CSS properties:
width,height,margin,padding,font-size, etc.
In short:
calc()lets you dynamically compute CSS values, combining percentages, pixels, and other units to create flexible and responsive designs.