How can I get a negative value of a CSS variables in a calc() expression?
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>
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.