The CSS calc() function
Learn how to work with the CSS calc() function
The calc()
function lets you perform basic math operations on values, and it’s especially useful when you need to add or subtract a length value from a percentage.
This is how it works:
div {
max-width: calc(80% - 100px)
}
It returns a length value, so it can be used anywhere you expect a pixel value.
You can perform
- additions using
+
- subtractions using
-
- multiplication using
*
- division using
/
One caveat: with addition and subtraction, the space around the operator is mandatory, otherwise it does not work as expected.
Examples:
div {
max-width: calc(50% / 3)
}
div {
max-width: calc(50% + 3px)
}
→ Get my CSS Handbook
→ I wrote 17 books to help you become a better developer:
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025