๐งฎ CSS Tutorial: calc()
๐ Introduction
The calc() function in CSS allows you to perform mathematical calculations directly inside your styles. It helps you create responsive layouts, mix units (px, %, rem), and build dynamic spacing without JavaScript.calc() is one of the most powerful tools in modern CSS! โจ
๐ฏ What Does calc() Do?
- Performs math inside CSS
- Supports +, โ, ร, รท
- Allows mixing units (%, px, rem, etc.)
- Useful for responsive components
- Works with variables using
var()
โจ Syntax
Syntax
property: calc(expression);Note
Add spaces around operators for best compatibility.
โ๏ธ
โ
โ๏ธ
calc(100% - 50px)โ
calc(100%-50px)๐งฉ Supported Operations
- + โ addition
- - โ subtraction
- * โ multiplication
- / โ division
๐ฅ Practical Examples
1. Responsive Width Calculation
Fluid Box
.box {
width: calc(100% - 40px);
}2. Mix px + % Units
Mixed Units
.container {
height: calc(100vh - 80px);
}3. Centering with calc()
Centered Element
.center {
margin-left: calc(50% - 150px);
}4. Using calc() with var()
calc() + var()
:root {
--sidebar: 240px;
}
.main {
width: calc(100% - var(--sidebar));
}5. Button Padding with calc()
Padding
.btn {
padding: calc(1rem + 4px) calc(2rem + 4px);
}6. Grid with Dynamic Columns
Flexible Grid
.grid {
grid-template-columns: repeat(3, calc(33.33% - 10px));
}7. Typography Scale
Font Scaling
h1 {
font-size: calc(1.5rem + 1vw);
}8. Dynamic Layout Adjustment
Sidebar + Content
.content {
margin-left: calc(var(--sidebar-width) + 20px);
}๐ Where You Can Use calc()
| Property Type | Examples |
|---|---|
| Length | width, height, margin, padding |
| Position | top, left, transform |
| Typography | font-size, line-height |
| Grid & Flex | grid-template, flex-basis |
๐ง Tips & Best Practices
- Always add spaces around operators
- Use
var()andcalc()together for flexible design tokens - Use in responsive typography (vw + rem)
- Use calc() to subtract fixed headers from full-page layouts
>>โcalc() gives you the freedom to blend fixed and fluid values โ unlocking truly responsive design.โ โจ
๐ Conclusion
The calc() function is an essential tool for building dynamic, responsive, and maintainable layouts. From fluid spacing to scalable typography and layout math, calc() lets you solve problems that were once impossible without JavaScript. Combine it with var() for even more powerful design systems. ๐