DEV Community

Cover image for How to perform calculations in CSS?
Hardique Dasore
Hardique Dasore

Posted on • Edited on

1

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

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay