What is calc() function in CSS?

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.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!