How can I get a negative value of CSS variables (aka Custom Properties)
Asked Answered
H

3

47

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?

Hanse answered 6/2, 2018 at 9:43 Comment(2)
"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.Ehrenberg
@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.Hanse
S
83

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>
Septa answered 6/2, 2018 at 9:47 Comment(2)
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?Nullipore
@TimR I wanted to have a double negationSepta
S
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.

Stokehold answered 11/3, 2020 at 11:13 Comment(0)
S
2

another possible way:

.negative-margin {
    margin-left: calc(0px - var(--margin));
}
Staley answered 3/4, 2023 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.