Inverting Pixel Value of CSS Variable

Viewed 2420

I'm using CSS variables, so that I can easily make sweeping changes. One of my variables is --gap: 15px, which I've used roughly 15 times so far. However, I now need to use the inverted value of --gap, which would be -15px.

Fails:

  1. calc(0 - var(--gap))
  2. calc(var(--gap) * -1)

Works:

  1. calc(var(--gap) - calc(var(--gap) * 2))

Questions:

  • The first attempt is clearly the most eloquent, but why doesn't work?

  • Is there a way to achieve this that is more eloquent than the third way?

1 Answers

Your first failure example works for me if I add units to the 0 part of the calculation.

From the spec:

Note: Because <number-token>s are always interpreted as numbers 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.

:root {
  --gap: 15px;
}

div {
  margin-top: calc(0px - var(--gap));
}
<div>text</div>

Your second failure example is working for me.

:root {
  --gap: 15px;
}

div {
  margin-top: calc(var(--gap) * -1);
}
<div>text</div>

I tested both examples in Firefox 64, Chrome 71, and Safari 12 (all Mac).

Related