Need to mix units or do quick math in your styles? With calc()
, you can perform calculations directly in CSS! This makes it easy to build fluid layouts, combine relative and absolute units, or adjust spacing on the fly — all without extra wrappers or complicated code. In this MiniCoursey quick guide, you’ll learn how calc()
works, see practical use cases, and pick up best practices for responsive, maintainable layouts.
What is CSS calc()?
calc()
lets you add, subtract, multiply, and divide values inside your CSS. It’s supported in all modern browsers and works with any valid units.
Basic Syntax
Wrap your math expression inside calc()
and mind the spaces around operators.
.sidebar {
width: calc(100% – 250px);
}
.button {
padding: calc(1rem + 2px);
}
In these examples, the sidebar fills the remaining space minus 250px, and the button’s padding combines a relative and fixed unit.
Why Use calc()?
- Mix flexible units (%, em) with fixed units (px, rem).
- Build layouts that adapt without extra containers.
- Fine-tune spacing with easy math in your CSS.
💡 Pro Tip: Always include spaces around operators like
+
and-
— they won’t parse otherwise!
⚠️ Common Mistake: Don’t overuse
calc()
when simpler solutions (like Grid or Flexbox) would work.
FAQ
Q: Can I use calc() in variables?
A: Yes! Combine calc()
with var()
for dynamic, DRY layouts.
Q: Does calc() impact performance?
A: Not really — it’s resolved at runtime but is fast and safe for production use.
Related Link
👉 Check out previous: CSS Variables — Write DRY, Scalable Styles
Where to Learn More
Visit MDN’s calc() docs for more tips and examples. Experiment with fluid sizing, margins, and spacing!
Conclusion
Congrats — you now know how to do simple math in your stylesheets with calc()
! It’s a small tool that unlocks big flexibility.
✨ Bookmark MiniCoursey for more quick & free mini courses!