Usage of calc() CSS function

The CSS calc() function allows you to perform mathematical calculations to determine CSS property values. It enables dynamic calculations using different units like pixels, percentages, em, rem, and viewport units.

Syntax

selector {
    property: calc(expression);
}

Possible Values

Operator Description Example
+ Addition calc(100px + 50px)
- Subtraction calc(100% - 20px)
* Multiplication calc(50px * 2)
/ Division calc(200px / 4)

Example: Dynamic Width Calculation

The following example creates a div that spans the full width minus 100px for margins −

<!DOCTYPE html>
<html>
<head>
<style>
    body {
        margin: 0;
        padding: 20px;
        font-family: Arial, sans-serif;
    }
    
    #demo {
        width: calc(100% - 100px);
        height: 60px;
        background-color: #2196F3;
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto;
    }
</style>
</head>
<body>
    <h2>Dynamic Width with calc()</h2>
    <div id="demo">Width: calc(100% - 100px)</div>
</body>
</html>
A blue box appears with white centered text, spanning the full width of the container minus 100px.

Example: Mixed Units Calculation

The following example demonstrates combining viewport units with fixed pixels −

<!DOCTYPE html>
<html>
<head>
<style>
    .container {
        height: calc(100vh - 80px);
        width: calc(50% + 100px);
        background: linear-gradient(45deg, #FF6B6B, #4ECDC4);
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 18px;
    }
</style>
</head>
<body>
    <div class="container">
        Height: calc(100vh - 80px)<br>
        Width: calc(50% + 100px)
    </div>
</body>
</html>
A gradient box appears taking full viewport height minus 80px and half width plus 100px, with centered white text displaying the calculation formulas.

Key Points

  • Spaces around operators are required: calc(100% - 20px) ?, calc(100%-20px) ?
  • Division by zero is invalid and will be ignored
  • Can mix different unit types in the same calculation
  • Nested calc() functions are supported

Conclusion

The calc() function is powerful for creating responsive layouts by combining different units. It's particularly useful for creating elements that adapt to container sizes while maintaining fixed spacing.

Updated on: 2026-03-15T13:25:59+05:30

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements