In which cases can calc () be used 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()

Syntax

It is important to respect the syntax of calc

height: calc(100% - 20px);

Although most browsers support a calc, 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);
}

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);
<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;
}
<div class="col-1"></div>
<div class="col-5"></div>
<div class="col-3"></div>

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>
Spread the love
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x