calc() function in CSS

If you are a website designer, you already heard about calc() in CSS, but being in CSS, where no code is executed, lots of users cannot get the idea of ​​when it should be used. Below is the simple example of calc()

Also Read: The correct CSS syntax for making all the elements bold?

CONTENTS

Syntax

It is important to know the syntax of calc

height: calc(100% - 20px);<gwmw style="display:none;">

Although most browsers support  calc, but it is a good practice to use a backup rule for browsers that do not:

.img-div {
  width: 85%; /* Override the width value */
  width: calc(100% - 100px);
}

Also Read: Which CSS property changes the font color of an element to blue?

Below are the several examples where it is much easier to do it by calc() than in any other way.

Background image positioning

It is quite simple to position a background image.

.img-div {
  width: 500px; 
  height: 500px;
  border: 1px solid black;
  background-image: url('url');
  background-repeat: no-repeat;
  background-position: 150px 50px;
}
<div class="img-div"></div>

But what happens when we want to position the background image in relation to the right and bottom sides and we don’t know in advance the size of the container element? We can get it by calc().

.img-div {
  width: 100%; 
  height: 500px;
  border: 1px solid black;
  background-image: url('url');
  background-repeat: no-repeat;
  background-position: calc(100% - 150px) calc(100% - 50px);
 }

Also Read: Expected RBRACE in CSS.

<div class="img-div"></div>

Creation of a GRID system

Imagine you want to design your own GRID system, let’s put 7 columns. This would cause that in CSS code we had decimal figures difficult to read and understand:

.col-1 {
  border: 1px solid black;
  width: 14.2857%;
  height: 50px;
}
.col-5 {
  border: 1px solid black;
  width: 71.4285%;
  height: 50px;
}
.col-3 {
  border: 1px solid black;
  width: 42.8517%;
  height: 50px;
}

We can make the code more readable and even almost “self-explanatory” by replacing the ugly decimals with the use of calc.

.col-1 {
      border: 1px solid black;
      width: calc(100% / 7);
      height: 50px;
    }
    .col-5 {
      border: 1px solid black;
      width: calc(100% / 7 * 5);
      height: 50px;
    }
    .col-3 {
      border: 1px solid black;
      width: calc(100% / 7 * 3);
      height: 50px;
    }
<div class="col-1"></div>
<div class="col-5"></div>
<div class="col-3"></div>
About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment