CSS
Negate a CSS variable
To use the negative value of a CSS variable, wrap it in the calc()
function and multiply it by -1
. Like this: calc(var(--my-variable) * -1)
.
For example:
If you have a margin variable set to 20px
and need to offset it in the opposite direction to -20px
(useful for things like overlapping layouts or compensating for padding):
:root {
--margin: 20px;
}
/* Set margin-left of the container to -20px */
.container {
margin-left: calc(var(--margin) * -1);
}
Note: Simply adding a minus (-
) sign in front of the variable (e.g. -var(--margin)
) will not work. The calc()
function is necessary for this operation.
This technique works in all modern browsers that support CSS custom properties (variables) and the calc()
function.