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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay