Menü schliessen
Created: November 4th 2021
Last updated: December 10th 2021
Categories: Common Web Development,  IT Development
Author: Tim Fürer

CSS Basics: Use calc() and var() to keep things flexible

Tags:  CSS,  CSS Basics
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

Keeping things flexible in CSS has become much easier with the introduction of functions such as "calc()" and "var()".

Unfortunately, despite their usefulness, I still rarely ever see them utilized. So, I'm writing this short guide to spread some awareness on them.


let's get to THE CSS

Imagine the following: You want to center an HTML element via "position: absolute". Its width and height are defined as 64px. Simple enough, no?

If this is your solution:

element
{
    position: absolute;
    top: 50%;
    left: 50%;
    width: 64px;
    height: 64px;
}

That's incorrect. The solution shown above will always be horizontally off by half of the element's width too much, and vertically off by half of the element's height too much. We need to subtract the excess width and height from the x and y coordinates.

So, how can we reliably know what 50% - 32px is?

The answer is: Through "calc()"!

element
{
    position: absolute;
    top: calc(50% - 32px);
    left: calc(50% - 32px);
    width: 64px;
    height: 64px;
}

This solution works and is about as far as most people would go. However, with the implementation of "var()", we can take things even further.

Take a look at the following:

element
{
    --element-width: 64px;
    --element-height: 64px;
    position: absolute;
    top: calc(50% - var(--element-width) / 2);
    left: calc(50% - var(--element-height) / 2);
    width: var(--element-width);
    height: var(--element-height);
}

As you can see, we've gotten rid of the statically defined halves of width and height in the position calculation by re-locating the element's width and height to a variable each, which allows us to get their values via the "var()" function and dynamically calculate the halves using "calc()".

This technique may be applied to other, similar problems (Full-Width element with margin):

Standard

element
{
    width: 96%;
    margin: 2%;
}

Optimized

element
{
    --element-margin: 2%;
    width: calc(100% - var(--element-margin) * 2);
    margin: var(--element-margin);
}

In conclusion: Use "calc()" and "var()"! Their benefits in elegance and flexibility are enormous and can save you from resorting to jank JavaScript solutions.

Helpful Resources