How to perform calculations in CSS?

hardiquedasore

Hardique Dasore

Posted on September 18, 2021

How to perform calculations in CSS?

If the user wants to perform mathematical operations in CSS such as multiplication, addition, subtraction or division, they can use calc() function in CSS.

calc() is a function that performs calculation to be used as the value of property.

Syntax

.class-name{
      property: calc(expression)
   }
Enter fullscreen mode Exit fullscreen mode

where expression is mathematical expression with + - * / operators. It can be used anywhere angle, length, frequency, number, integer, time or percentage is required.

calc() can be used as an alternative to grid but it's not recommended to do the same.

Points to remember before you use calc()

• Only + and - operators should be surrounded by whitespaces.

calc(50% - 80px)
Enter fullscreen mode Exit fullscreen mode

• You can now use calc() with media query.
calc() is mainly used when working with mixed units.

width: calc(50rem - 3px);
Enter fullscreen mode Exit fullscreen mode

• You can nest calc(calc())

.class-name {
  width: calc(
    calc(20% / 5)
    +
    calc(4rem * 2)
  );
}
Enter fullscreen mode Exit fullscreen mode

Image description

Follow us on Instagram

💖 💪 🙅 🚩
hardiquedasore
Hardique Dasore

Posted on September 18, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related