43

Let me start by showing you how I would do this in SCSS:

$submenu-padding-left: 1.5em;

transform: translateX(calc(-#{$submenu-padding-left} + .5em));

which would compile to:

transform: translateX(calc(-1.5em - .5em))

Basically SCSS allows me to concatenate a minus symbol - with a variable in order to convert it to a negative value.

Is it possible to achieve this with CSS Variables?

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
IOIIOOIO
  • 3,899
  • 4
  • 14
  • 19
  • 1
    "How to concatenate a minus symbol with CSS Variable in a calc()" As you've seen, that's not the correct way to approach the problem. You never concatenate anything in a calc() expression. You can, however, concatenate var() expressions just about everywhere else. – BoltClock Feb 06 '18 at 09:51
  • @TemaniAfif That is a fair point, both answers are basically the same - because you answered first I have marked your answer as the accepted one again. – IOIIOOIO Mar 16 '20 at 11:33

3 Answers3

74

Yes you can do it. Simply multiply by -1:

:root {
  --margin: 50px;
}

body {
  margin: 0 100px;
  border:1px solid;
}

.box-1 {
  background: red;
  height: 100px;
  width: 200px;
  margin-left: calc(-1 * var(--margin));
}

.box-2 {
  background: green;
  height: 100px;
  width: 200px;
  margin-left: calc(-1 * (-1 * var(--margin))); /* You can also nest calculation */
}
<div class="box-1">
</div>
<div class="box-2">
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • Did you intentionally show a calc() example that negated itself? `margin-left: calc(-1 * (-1 * var(--margin)));` is the same as `margin-left: var(--margin);` Perhaps `margin-left: calc(2 * (-1 * var(--margin)));` would be a better demonstration? – Tim R May 14 '23 at 01:55
  • @TimR I wanted to have a double negation – Temani Afif May 14 '23 at 07:28
9

If you need negative value multiple times then you can define a new variable:

:root {
  --margin: 50px;
  --margin--: calc(var(--margin) * -1);
 /* 
 while you may simply write like below
 but I love to use as above 
 coz, we'll only need to change value 
 in one place if needed
 */
 /* --margin--: -50px; */
}

.positive-margin {
  margin: var(--margin);
}
.negative-margin {
  margin-left: var(--margin--);
}

You can use --margin- or --negative-margin instead of --margin--. But I preferred this because of readability.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
0

another possible way:

.negative-margin {
    margin-left: calc(0px - var(--margin));
}