What is calc() function in CSS?

The calc() function in CSS allows you to perform mathematical calculations when specifying property values. It is particularly useful in situations where you need to combine different units or perform simple arithmetic operations to determine a property value. Thecalc() function can be used with length values, percentages, and other numeric values.

Here's a simple example of using calc() in CSS:

/* Using calc() to set the width of an element */
.container {
  width: calc(50% - 20px); /* 50% of the parent width minus 20 pixels */
}

/* Using calc() with different units */
.box {
  height: calc(100vh - 50px); /* 100% of the viewport height minus 50 pixels */
  margin-left: calc(20px + 2em); /* 20 pixels plus 2 times the font size */
}

In these examples, calc() is used to perform arithmetic operations on values. You can use +, -, * (multiplication), and / (division) within the calc() function.

It's important to note that spaces are required around the + and - operators, but they are optional around * and /. Here are a few more examples:

/* Using calc() with different units and operators */
.element {
  width: calc(100% - 20px); /* Subtracting 20 pixels from 100% */
  font-size: calc(16px + 1em); /* Adding 1em to 16 pixels */
  line-height: calc(1.5 * 1.2); /* Multiplying 1.5 by 1.2 */
}

Conclusion:

The calc() function enhances the flexibility of CSS by allowing dynamic calculations, making it easier to create responsive and adaptive layouts.

0
Subscribe to my newsletter

Read articles from LingarajTechhub All About Programming directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

LingarajTechhub All About Programming
LingarajTechhub All About Programming

Corporate Software Development Trainer with a demonstrated track record of success in the IT and Ed-tech industries for product development. I started my career as a software developer and have since taught C, C++, Java, and Python to hundreds of IT enthusiasts, including corporate professionals, throughout the years. I have been developing software for over 12 years.