With the help of the calc() function, we can do simple math right in our stylesheets.
This function is not the newest part of the CSS specs. Although it is a tiny part of our toolkit, it deserves a short introduction. Using calc() function is easy, you write up your mathematical operations and wrap them in the function.
left: calc(50vh - 100px);
From this example, we can see a lot of things let’s discuss them!
What Does the Calc() Function Do?
In short, it makes it possible for us to make mathematical operations in your stylesheets. We can use the four basic mathematic operations: addition (+), subtraction (-), multiplication (*), division (/).
Addition and subtraction can be comfortable in a programing language, but in CSS, it was a problem. We only could use exact values. Even though it was a needed method here too, we only could use preprocessors but with more limitation.
Need a Laravel expert? We can help you to create your next performance-based, scalable, and robust project.
The Difference Between Calc() and Preprocessor Operations
The calc() function’s result happens at render time. It isn’t a real value; it is an expression. Hard to imagine this is you aren’t a front-end developer and don’t know about the browser’s rendering.
If you calculate something in Sass/SCSS, you get a value after the compile. Doing the same with calc() doesn’t give back the result of the operation (the result will be some kind of live value).
This technique can be handy when you are making an admin template where you need a fixed sidebar which is always visible. For this, you make a sidebar with 260px width and set the rest of the layout width calc(100% – 260px).
Simplifying Absolute Centering
We all know that the most fundamental absolute centering is when we set 50% top and left value and pull back the element with both of the halves of the width and height with using the margins.
With the introduction of the vw and vh units, now we always can get our current viewport width and height. Knowing this can be useful when we want to make a responsive square, but it is also useful when we wish responsive font-size.
In this situation, the previous solution can be a fallback because now we have an even better solution. The background-position property can have two optional parameters which define the offset axis like this:
background-position: right 20px bottom 20px;