The calc() function in CSS allows us to perform mathematical calculations directly in CSS expressions. It can be used to calculate values ??for various CSS properties such as width, height, padding, etc.

The syntax of the calc() function is relatively simple. We can use mathematical operations such as addition (+), subtraction (-), multiplication (*), and division (/) to calculate values. Here is an example:

div {
  width: calc(100% - 20px);
  height: calc(50vh + 10%);
}

This example sets the width of the div element to 100% of the available width minus 20 pixels. The height is set at 50% of the available amount plus 10%.

The calc() function also supports the use of units such as pixels (px), percent (%), viewport height (vh), and viewport width (vw). We can also combine different units in one calculation.

// combine different units
height: calc(50vh - 20px);

//With different units and operations
font-size: calc(16px + 2vw);

//In combination with variables
:root {
  --margin: 10px;
}
margin: calc(var(--margin) * 2);

Fazit:

The calc() function is particularly useful if we want to create responsive designs or calculate dynamic values ??based on other CSS properties.

but, It is important to note that the calc() function cannot be used in all CSS properties. For example, it cannot be used in properties such as content, display or position.

Using the calc() function can greatly improve the flexibility and convenience of creating CSS layouts, as it allows complex calculations to be performed directly in CSS

Let’s see one last time the calc() function in use.

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      .content-container {
        display: flex;
        padding: 40px 0;
        background-color: #d7dade;
      }
      .right {
        width: 100px;
        background-color: #759ac9;
      }
      .left {
        width: calc(100% - 100px);
        background-color: #7cd47b;
      }
    </style>
  </head>
  <body>
    <div class="content-container">
      <div class="left">Some text</div>
      <div class="right">Some text</div>
    </div>
  </body>
</html>
Result:

In the example above, we set the display property of the container to “flex”. For the right <div> element, we specified the width, while for the left <div>, we used the calc() function to calculate its width.

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *