5

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.

2 Answers2

6

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>
Harry
  • 80,224
  • 23
  • 168
  • 185
  • After putting `left: calc(var(--skyve-bredde) * -1);` it does not appear it equals `left: -50%;`. What am I doing wrong? *EDIT* It worked! Thank you! – user3774924 Nov 14 '16 at 09:40
  • @user3774924: Can you please show me a demo so that I can see what is going wrong? I just tried a sample and it is calculating correctly. – Harry Nov 14 '16 at 09:42
1

I haven't ever used CSS variables like that, but logically just reversing the value should work:

right: calc(var(--skyve-bredde) * -1);
Angel Politis
  • 9,949
  • 12
  • 43
  • 62