Could we help you? Please click the banners. We are young and desperately need the money
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.
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.