9

I'm using calc() to set the top: attribute in a class. I need some help understanding how calc() gets used - two equations I believe should have the same result don't. (The top equation isn't practical, I'm just trying to debug a larger issue and noticed these two don't have the same result)

calc(-10px + ((1 - 1) * 0));

calc(-10px);
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
nbixler
  • 490
  • 1
  • 9
  • 24

1 Answers1

7

The first equation is invalid because it will lead to calc(-10px + 0)

Note: Because <number-token>s are always interpreted as <number>s or <integer>s, "unitless 0" <length>s aren’t supported in calc(). That is, width: calc(0 + 5px); is invalid, even though both width: 0; and width: 5px; are valid. ref

And if the result was non-zero you will fall into this:

At + or -, check that both sides have the same type, or that one side is a <number> and the other is an <integer>. If both sides are the same type, resolve to that type. If one side is a <number> and the other is an <integer>, resolve to <number>.

The last one is more logical since 10px + 5 has no meaning whearas we may think that 10px + 0 is simply 10px but for the browser it's not.

Related question: Why doesn't min() (or max()) work with unitless 0?

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • That makes sense, thanks! My follow up question: how do I need to reformat ```top: calc(-10px - (100% - 627px));``` to be valid/usable? – nbixler Mar 28 '19 at 20:26
  • 1
    @nbixler it seems valid for me since your are using a mix of % and px that can work together – Temani Afif Mar 28 '19 at 20:27
  • Update: Started working when I switched from % to vw (I know they aren't interchangeable, so I had to reconfigure my equation a bit). – nbixler Mar 28 '19 at 21:10
  • 1
    @nbixler I forget something ... % with px should work BUT there is another issue which is that top value using % will not work if the parent element don't have a height set. So calc is valid but the issue is somewhere else. You can test the % without calc and you will face the same thing – Temani Afif Mar 28 '19 at 21:19