user3774924 user3774924 - 26 days ago 7
CSS Question

Make variable value negaitve

I am trying to figure out a way to make a variable negative.
I have attempted

right: calc(0-var(--skyve-bredde));
bit it did not work.
This is the variable:

#drawer, #burger{
--skyve-lengde:50%;
}


The value will be used in
right
and
width
attributes.
Any help is appreciated, thank you.

Answer

Reason for the code in question not working: (all emphasis within quoted text are mine)

right: calc(0-var(--skyve-bredde));

The above wouldn't work for two reasons and they are as follows:

  • As per CSS calc() syntax there must be a space before and after the + or - operator.

    In addition, white space is required on both sides of the + and - operators. (The * and / operaters can be used without white space around them.)

  • As per Type Checking for CSS calc, 0 is a <number> whereas the other value is <percentage>. For properties like width, left, right etc, the <percentage> takes the <length> type and so the below check would fail (as the values are not of the same type) and so the expression will be treated as invalid.

    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>.

    If an operator does not pass the above checks, the expression is invalid.


Solutions:

  • As already mentioned in the above answer and the comment, calc(var(--skyve-bredde) * -1) will work and produce the expected output.
  • Or alternately using the same type on either side, like calc(0% - var(--skyve-bredde)) should also work.

:root {
  --skyve-bredde: 50%;
}
div {
  position: absolute;
  right: calc(0% - var(--skyve-bredde));
  background: red;
}
<div>Some text</div>


Adding a negation symbol before the variable:

This will not work if my understanding of the spec is correct. Refer the second code block under Example 11 and the explanation. According to that -var(--skyve-bredde) would only become - 50% which is not a valid value and would hence result in an Invalid Property Value error.

:root {
  --skyve-bredde: 50%;
}
div {
  position: absolute;
  right: -var(--skyve-bredde);
  background: red;
}
<div>Some text</div>