How to get a unit-less result of the calc() function

Viewed 1149

I am using this calculation to get a fluid line-height in my webpage:

line-height: calc(1.42em + (1.55 - 1.42) * ((100vw - 300px) / (1080 - 300)));

And the math is working property except if I change the font-size of an specific section (since the line-height should be stated with a unit-less number in order to preserve the font-size/line-height ratio).

The question is: How do I get a unit-less result from this calculation?

I have tried removing the em and the px units, but that break the effect.

If I didn’t use this calculation, I would probably use something like:

body {
    font-size: 18px;
    line-height: 1.4;
}

I can get the calc() function to return 18px, for example. But how do I get the calc() function to return an unit-less result (like: 1.4) when I am using other multiple units inside it. Any way to convert the result in a unit-less number?


This is the whole CSS:

:root {
    --font: calc(16.2px + (18 - 16.2) * ((100vw - 300px) / (1080 - 300)));
    --verti: calc(1.42em + (1.55 - 1.42) * ((100vw - 300px) / (1080 - 300)));
}

html {
    font-family: "Georgia";
    font-size: var(--font);
    line-height: var(--verti);
}

.small {
    font-size: 0.8em;
}

This work great. But, the line-height of the class .small is to big. And I can either do another calc() function just for it, or have the preview calc() to return its value with a unit-less number.

1 Answers

It's not possible to get a unit-less value out of calc() if any of your inputs have units.

However in this particular case with line-height specifically, it should be noted that the unit-less value of line-height: 1.4 is equivalent to line-height: 140%. Likewise 3.1 is equivalent to 310% and etc. You should be able to modify your calc() equation to output the desired value with the % unit.


Edit: It seems inheritance behaves differently for unit-less and percent values, so use this approach with caution. It should be OK if you avoid specifying line-height on parent elements. https://developer.mozilla.org/en-US/docs/Web/CSS/line-height#Prefer_unitless_numbers_for_line-height_values

Related