Open In App

Explain the working of calc() function in CSS

The CSS calc() function is an inbuilt function that is used to perform calculations based on CSS property.

Working of calc() function: The calc() is an inbuilt CSS function, with the purpose to perform calculations while specifying CSS property values. It can be used where a frequency, length, number, time, etc. is allowed. More specifically, the calc() function is used in providing values.



Syntax : 

selector{
  property-name: calc(Expression)
}

Parameters: The calc() function accepts a mandatory single parameter expression. The value passed must contain a mathematical expression. 



 

The basic mathematical operators that can be used in the expression are as follows.

We can use different units for each value in the expression.

Syntax Technicalities : 

Working: Calculations made by the calc() function of CSS are based on the values provided by the user during the calculation.   If it is not provided the calculation is done based on the values of their parent element.

Example 1: In the below example, the height to the container is set to 1/3 of 100% of viewport height, and width is set to 1/2 of 80% of the viewport width. The exact value in units is unknown. We use calc() which will provide the desired height and width to the container.




<!DOCTYPE html>
<html lang="en">
  
<head>
    <title>Using Calc</title>
    <style>
        .container {
            height: calc(100vh / 3);
            width: calc(80vw / 2);
            background-color: green;
            font-family: cursive;
            color: white;
            text-align: center;
            font-size: 2.3rem;
            margin: auto;
            font-weight: bold;
        }
    </style>
</head>
  
<body>
    <div class="container">
        GeeksforGeeks
    </div>
</body>
  
</html>

Output:

Example 2:  In the below example, we have two containers, a parent container, and its child container. The exact values for height and width for the parent container are known. We want to calculate height and width relative to the parent container. So use calc() to easily specify the desired height and width to the child container.




<!DOCTYPE html>
<html>
<head>
    <title>Using Calc</title>
    <style>
        * {
            box-sizing: border-box;
        }
          
        .parent {
            height: 12rem;
            width: 25rem;
            background-color: #a29bfe;
            margin: auto;
        }
          
        .child {
            height: calc(100% / 2);
            width: calc(50% - 20px);
            background-color: green;
            color: white;
            text-align: center;
            font-family: cursive;
            font-size: 1.2rem;
        }
    </style>
</head>
  
<body>
    <div class="parent">
        <div class="child">GeeksforGeeks</div>
    </div>
  
</body>
  
</html>

Output:


Article Tags :