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

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>

Leave a Comment