Tuesday, August 2, 2022
HomeWeb DevelopmentHow and when to make use of CSS calc(): Tutorial with examples

How and when to make use of CSS calc(): Tutorial with examples


Have you ever heard of or used the CSS calc() operate? Maybe you might have heard about it however by no means tried it, or have tried utilizing it however bumped into some points alongside the best way. This information can assist you out.

CSS calc() is a good device that will help you optimize your internet pages. On this tutorial, we’ll take a look at the CSS calc() operate, why it’s helpful, and tips on how to use it in your initiatives. We’ll cowl the next:

Let’s get began.

What’s the CSS calc() operate?

The calc() operate permits you to carry out computations when specifying CSS property values. It’s particularly helpful for calculating size, share, time, numbers, integers, frequencies, and angles, amongst different issues.

One of many CSS calc() operate’s superpowers is the flexibility to mix totally different items. This operate can carry out math calculations that the preprocessor can’t.

Preprocessors in CSS can solely mix items which have a hard and fast relationship, resembling angular items, time items, frequency items, decision items, and particular size items.

Allow us to now study the CSS calc() syntax:

calc( Expression)

The calc() operate takes a single expression as its parameter. The results of the expression is then used as the worth. It could actually take any type and make use of any of the next operators, following customary operator priority guidelines.

The calc() operate makes use of 4 fundamental operators:

Addition +:


Extra nice articles from LogRocket:


calc(50px + 50px)

Subtraction –:

calc(100% - 30px)

Division /:

calc(100% / 2)

Multiplication *:

calc(100vh * 2)

Let’s take a look at some fundamental examples of utilizing the CSS calc() operate. Then, we are going to discover some issues to notice about this operate, after which we are going to dive into some extra difficult examples.

Instance of unit conversion in CSS utilizing calc()

With the CSS calc() operate, we will convert a price with no items into a price with items by multiplying the worth by the unit sort you wish to convert to. This may be helpful with CSS variables, as within the instance beneath:

.class {
  --fav-num: 3;
  width: calc(var(--fav-num) * 1px); // 3px
}

On this instance, we assigned the quantity 3 — which has no unit hooked up to it — the CSS variable --fav-num. We then used it to get a brand new width worth with a unit by multiplying it by 1px to grow to be 3px.

Instance of changing font sizes with calc()

Let’s say we now have a situation during which we would like our paragraph’s font to be massive on a desktop display however small on a cellular display. After all, CSS media queries can assist, however the calc() operate can also be equal to the duty, so we gained’t want to make use of media queries.

Let’s see the way it goes:

p {
    font-family: Arial, Helvetica, sans-serif;
    font-size: calc(10px + 5vw);
}

This can permit our fonts to be smaller in a cellular view and return to regular once we enhance the display measurement or in a desktop view.

Please be aware that this method shouldn’t be used in case your font measurement is already small for the desktop view; in that case, it wouldn’t make sense to make the font measurement even smaller for the cellular view.

Some issues to notice concerning the CSS calc() operate

Let’s now check out just a few issues to notice when utilizing the CSS calc() operate.

First, when writing the calc() operate syntax, we should embody an area between every operation — particularly when utilizing the + and – operators — or our expression will likely be invalid. Think about the next instance:

calc(50% -4px)

The expression above is invalid as a result of we didn’t embody an area between the operator and the size, making the size seem detrimental. To appropriate the expression, we would wish to put in writing it as follows:

calc(50% - 4px)

Observe that though the * and / operators don’t require whitespace, together with areas is permissible. It’s due to this fact advisable to incorporate areas for consistency.

Listed below are just a few extra issues to notice concerning the CSS calc() operate:

  • It doesn’t work when utilized to media queries
  • The HTML parser generates an error while you divide by zero
  • It’s potential to nest the calc() operate

Let’s dive into some extra examples.

Instance of adjusting positioning and size in CSS with calc()

To know tips on how to alter positioning and size utilizing the CSS calc() operate, let’s begin by making just a few playing cards and putting them inside a container.

You will want the next for the HTML:

 <div class="container">
       <div class="card"><p>card 1</p></div>
       <div class="card"><p>card2</p></div>
       <div class="card"><p>card3</p></div>
       <div class="card"><p>card4</p></div>
       <div class="card"><p>card4</p></div>
    </div>

Your CSS code ought to appear to be this:

*{
    margin: 0;
   padding: 0;
   box-sizing: border-box;
}
physique{
    show: flex;
    justify-content: heart;
    align-items: heart;
    min-height: 100vh;
}
.container{
    place: relative;
    show: flex;
    width: 1000px;
    top: 200px;
    background:#ccc
}
 .card{
    place: relative; 
    min-width: 200px;
    top: 200px;
    background:#FF0000;
    margin: 10px 10px 10px 10px;
    coloration: white;
    font-family: 'Franklin Gothic Medium', 'Arial Slim', Arial, sans-serif;
}

The consequence:

Five Red Cards Of Equal Size On Top Of But Overflowing And Not Aligned With A Gray Container

Do you discover how our purple playing cards don’t align with the grey container? Let’s now introduce the CSS calc() operate by utilizing it on our min-width and top inside our playing cards:

 min-width: calc(calc(100% / 5) - 20px);
 top: calc(100% - 20px);

For our min-width, we nested a calc() operate inside one other calc() operate. The nested CSS operate was used to divide the complete width of the display (100%) by 5, and the consequence was then multiplied by 20px to get the ultimate worth for our min-width.

For our top, we subtracted the whole worth of the highest and backside margins (which is 20px) from 100% of the peak, leading to a wonderfully aligned field.

The consequence:

Five Red Cards Of Equal Size Aligned Over Gray Container

As you possibly can see, the purple playing cards are actually positioned inside our container completely!

We will additionally use the CSS calc() operate in a sneaky sort of means. Let’s see how within the subsequent instance, the place we are going to discover two circumstances of utilizing this operate in a pattern weblog.

Alternative ways to make use of CSS calc() in a pattern weblog

For our subsequent instance, I created a easy pattern weblog with a scroll bar, some dummy paragraphs, and a picture. We’ll use this pattern weblog to clarify circumstances the place we will use the CSS calc() operate.

To arrange our pattern weblog, our HTML ought to appear to be this:

<header>
      <nav>
        <span>house</span>
        <span>about</span>
        <span>contact</span>
      </nav>
    </header>
    <div class="container">
      <div class="blog-container">
        <part class="part">
          Sed ut perspiciatis unde omnis iste natus error sit voluptate
          accusantium doloremque laudantium, totam rem aperiam, eaque 
          ab illo inventore veritatis et quasi architecto beatae vitae 
          dsunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit
          aspernatur aut odit aut fugit, sed quia consequuntur magni do
          qui ratione voluptatem sequi nesciunt. Neque porro quisquam e
          dolorem ipsum quia dolor sit amet, consectetur, adipisci veli
          quia non numquam eius modi tempora incidunt ut labore et dolo
          aliquam quaerat voluptatem. Ut enim advert minima veniam, quis n
          exercitationem ullam corporis suscipit laboriosam, nisi ut al
          ea commodi consequatur? Quis autem vel eum iure reprehenderit
          ea voluptate velit esse quam nihil molestiae c onsequatur, ve
          qui dolorem eum fugiat quo voluptas nulla pariatur?
          <img src="https://picsum.images/200" class="my-image" />
        </part>
        <part>
          Sed ut perspiciatis unde omnis iste natus error sit voluptat
          accusantium doloremque laudantium, totam rem aperiam, eaque i
          ab illo inventore veritatis et quasi architecto beatae vitae 
          sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit
          aspernatur aut odit aut fugit, sed quia consequuntur magni do
          qui ratione voluptatem sequi nesciunt. Neque porro quisquam e
          dolorem ipsum quia dolor sit amet, consectetur, adipisci veli
          quia non numquam eius modi tempora incidunt ut labore et dolo
          aliquam quaerat voluptatem. Ut enim advert minima veniam, quis n
          exercitationem ullam corporis suscipit laboriosam, nisi ut a
          ea commodi consequatur? Quis autem vel eum iure reprehenderit
          ea voluptate velit esse quam nihil molestiae consequatur, vel
          qui dolorem eum fugiat quo voluptas nulla pariatur? Sed ut
        </part>
      </div>
    </div>

Our CSS code ought to appear to be this:

*,
*::earlier than,
*::after{ 
  margin: 0;
  padding: 0;
    box-sizing: border-box;
}
header{
  width: 100%;
  top: 60px;
  padding: 20px;
  background: #CBC3E3;
  coloration: white;
  font-family: Arial, Helvetica, sans-serif;
  show: flex;
  align-items: heart;
  box-sizing: border-box;
}
.blog-container{
 font-size: 1.5rem;
  max-width: 1000px;
  width: calc(90vw -20px) ;
margin: 20px auto;
}

  img{
    show: block;
    max-width: 100%;
  padding-top:30px;
  }

Now that our pattern weblog is about up, we will start exploring use circumstances for the CSS calc() operate.

Utilizing CSS calc() to repair our navbar place

We’ve a navbar on the weblog, however as you possibly can see beneath, the scroll bar on the proper overlaps with it:

Sample Blog With Navbar Overlapped By Scroll Bar On Right Side

What if we wished the navbar’s place to be mounted in order that the scroll bar doesn’t overlap with it? There are numerous methods to realize this, together with utilizing the CSS calc() operate:

.container{
  top: calc(100vh - 60px) ;
overflow-y: auto;
}

The consequence:

Sample Blog With Adjusted Navbar And Scroll Bar No Longer Overlapping

Within the code above, we created a container selector in our CSS and gave it a view top of 100 — the viewport of our whole window — after which subtracted the peak of our header from it. Our adjustments wouldn’t work except we set an overflow worth.

Utilizing CSS calc() so as to add a full-width picture

Let’s say we would like the picture in our weblog to refill the areas on either side of our weblog’s content material as a substitute of staying inside the weblog container’s margins. Once more, we will use the CSS calc() operate for that:

.my-image{
  max-width: 100vw;
  width: 100vw;
  margin: 0 calc(-50vw + 50%);
  top: 70vh;
}

The consequence:

Sample Blog With Image Filling Full Viewport Width With Dummy Text Above And Below

Within the code above, we set the margins to 0 for the highest and backside. Nevertheless, on the left and proper, we did one thing uncommon: we used the calc() operate to present it a detrimental viewport width (- 50vw) after which added 50 p.c again in.

In consequence, we now have our picture that fills the complete viewport. No matter the truth that it’s housed in the identical container as our part, our picture is now taking the complete width of the display.

Instance of utilizing the calc() operate with CSS variables

Utilizing calc() with CSS variables, we will outline a price as soon as and modify it utilizing math with a view to get a brand new worth which will likely be helpful for us. Let’s check out an instance.

Suppose we now have two buttons, every with its personal class, like so:

 <div class="container">
   <button class="success">button 1</button> 
   <button class="hazard">button2</button>
   </div>

We will use a CSS variable to outline one coloration after which use the CSS calc() operate to derive one other coloration. Let’s create a coloration variable for our button. We’ll be utilizing hsl notation, which takes the variables (hue, saturation, lightness) to specify a coloration worth:

:root{
    --hue:180;
}
.success{
 background-color: hsl(calc(var(--hue)), 100%, 50%);
}
.hazard{
    background-color: hsl(calc(var(--hue) - 180), 100%, 50%);
}

End result:

Two Buttons Side By Side Labeled Button 1, Which Is Teal Colored, And Button 2, Which Is Red Colored

By giving our root hue a particular worth, you possibly can see that we will use the calc() operate inside our hsl notation to derive one other coloration for the second button. If we alter the worth of our root hue, one other coloration is derived for the second button.

Can we use CSS calc() for animations?

We will in fact use the CSS calc() operate to make animations. Let’s create an instance! Begin with the next HTML:

<part>
      <div class="animate-loading">
        <div class="block" fashion="--i: 1"></div>
        <div class="block" fashion="--i: 2"></div>
        <div class="block" fashion="--i: 3"></div>
        <div class="block" fashion="--i: 4"></div>
        <div class="block" fashion="--i: 5"></div>
        <div class="block" fashion="--i: 6"></div>
        <div class="block" fashion="--i: 7"></div>
        <div class="block" fashion="--i: 8"></div>
        <div class="block" fashion="--i: 9"></div>
        <div class="block" fashion="--i: 10"></div>
        <div class="block" fashion="--i: 11"></div>
        <div class="block" fashion="--i: 12"></div>
        <div class="block" fashion="--i: 13"></div>
        <div class="block" fashion="--i: 14"></div>
        <div class="block" fashion="--i: 15"></div>
        <div class="block" fashion="--i: 16"></div>
        <div class="block" fashion="--i: 17"></div>
        <div class="block" fashion="--i: 18"></div>
        <div class="block" fashion="--i: 19"></div>
        <div class="block" fashion="--i: 20"></div>
      </div>
    </part>

Our CSS ought to appear to be this:

root
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Courier New', Courier, monospace;
}
part{
    show: flex;
    justify-content: heart;
    align-items: heart;
    min-height: 100vh;
    background: #001d10;
}
.animate-loading{
     place: relative;
     width: 250px;
     top: 250px;
}
.animate-loading .block{
    place: absolute;
    width: 8px;
    top: 25px;
    background: #050c09;
    left: 50%;
    border-radius: 8px;
    rework: rotate(calc(18deg * var(--i)));
    transform-origin: 0 125px ;
    animation: animate 1.9s ease-in-out infinite;
    animation-delay: calc(0.05s * var(--i));
}
@keyframes animate {
    0%,50%{
         background: #050c09;
         box-shadow: none;
    }
    50.1%,100%{
        background: #38d2dd;
        box-shadow: 0 0 5px #38d2dd,
                    0 0 15px #38d2dd,
                    0 0 30px #38d2dd,
                    0 0 60px #38d2dd,
                    0 0 90px #38d2dd;

    }
}

The consequence:

Animated Loading Circle With Dark Green Background And Tick Marks Animated To Light Up In Teal Successively Around The Circumference Of The Circle

As we will see within the code, the CSS calc() operate got here in helpful in two areas: to animate our rotation, and in addition for our animation delay. Let’s take a better take a look at these two areas.

rework: rotate(calc(18deg * var(--i)));

The worth of 18deg comes from dividing 360 levels by the variety of blocks we created in our HTML. We then bought the rotation worth for our rework by multiplying 18deg by the worth of our variable.

animation-delay: calc(0.05s * var(--i));

We additionally used the CSS calc() operate in our animation-delay by multiplying 0.05s by our variable. This was used to specify the delay earlier than the beginning of our animation.

Browser compatibility for CSS calc()

Whereas calc() is a helpful operate in CSS, it’s solely helpful when it’s appropriate with our browser. Check out the chart beneath to see browser compatibility for this operate:

Browser Compatibility Chart For Css Calc Function

You may take a look at CanIUse for extra particulars on browser compatibility for the CSS calc() operate.

When must you use the CSS calc() operate?

There are a whole lot of instances we’ll be needing the CSS calc() operate to save lots of us. They embody:

  • Once we are working with CSS variables
  • For deriving a brand new worth
  • For calculations between totally different items, which is one thing a preprocessor can’t do
  • For positioning
  • For tweaks on our web site’s construction and different components
  • Once we wish to keep away from making the identical calculations repeatedly

Many of the examples we lined on this article fall underneath the classes said above.

Conclusion

There are tons of the way we may use the CSS calc() operate. You could possibly even provide you with your use circumstances, too. The CSS calc() operate is basically one thing that you must check out. It’s a vital device within the internet developer’s toolbox.

Should you discovered this text useful, please share it!

Is your frontend hogging your customers’ CPU?

As internet frontends get more and more advanced, resource-greedy options demand increasingly more from the browser. Should you’re fascinated with monitoring and monitoring client-side CPU utilization, reminiscence utilization, and extra for your whole customers in manufacturing, strive LogRocket.https://logrocket.com/signup/

LogRocket is sort of a DVR for internet and cellular apps, recording all the pieces that occurs in your internet app or web site. As an alternative of guessing why issues occur, you possibly can mixture and report on key frontend efficiency metrics, replay consumer periods together with software state, log community requests, and mechanically floor all errors.

Modernize the way you debug internet and cellular apps — .

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments