Nested calc operations
Asked Answered
N

3

32

Hopefully this is quite simple. I want to use the CSS calc operation to perform two calculations:

I want to set my width to the equivalent of

(100% / 7) - 2

However if I try to perform more than one operation in a CSS calc operation, it fails:

width: calc((100% / 7) - 2);

How can I perform multiple calc operations in one CSS statement?

Nobie answered 22/12, 2013 at 18:11 Comment(2)
I'd consider LESS or another preprocessor if I were you.Dander
Or you can just divide 100 by 7 and subtract 2Venusberg
N
54

Apparently you have to assign px or % to all numbers that are not being multiplied or divided.

width: calc((100% / 7) - 2px);

Well I feel dumb now. Haha.

Nobie answered 22/12, 2013 at 18:15 Comment(3)
Do all browsers support nested calc() expressions?Circumlocution
Just to clarify, it doesn't have to be px or %. It could also be em, rem, etc...Moreira
Unfortunately IE still doesn't support nested calc() expressions @CircumlocutionAnthropoid
C
8

As David already stated, calc requires px, % or some kind of unit to work. It is possible to use multiple calculations in one statement just like:

width: calc((100% / 7) - 2px);

For anyone else visiting this page looking for answers, it may be worth mentioning that it can be ANY unit. That is, not just px and %, but also em, rem, vh, vw, vmin, vmax, etc. Calc resolves into a value you could use normally, so in the same way you'd never assign width: 100; you should never let the result of calc be unitless.

When dividing or multiplying, it doesn't really make sense to use units on both sides, but it still requires one of the numbers to have a unit so it knows what to assign the result.

/* These are wrong */
width: calc(75 + 25);
width: calc(4 * 20);
width: 100;

/* These are what the browser expects */
width: calc(75px + 25px);
width: calc(20px * 4);
width: 100px;
Concoction answered 18/2, 2018 at 20:2 Comment(0)
I
5

I also had a lot of headache when I tried to do that, but fortunately there's an alternative. Instead of writing it all in a single line, you could also use pure css variables using var(), which aside from solving this problem, is also much more readable! Here's an example of how I used it:

#wrapper .leftside .week .superior {
    --wholeWidth: calc(157px * 3);
    --remaining: calc(100% - var(--wholeWidth));
    margin: 0 calc(var(--remaining) / 6);
}

I found it under the "Nested calc() with CSS Variables" in the MDN docs.

Inveigle answered 17/2, 2020 at 5:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.