How to Use Negative Value for CSS Variable

How to Use Negative Value for CSS Variable

It is very easy to do negative margins with CSS, but do you know how to make CSS variables negative?

How to Get a Negative Value of CSS Variable

This is how we can specify negative margin with CSS:

	
		.negative-margin {
			margin-top: -10px;
		}
	

Let’s convert above CSS margin into CSS variable:

	
		:root {
			--margin-top: 10px;
		}

		.negative-margin {
			margin-top: var(--margin-top);
		}
	

The only problem with the above code is that it doesn’t work. Putting a negative sign in front of a CSS variable does not negate its value.

How to Get Negative Margin in CSS Using Variables

You can have a negative margin variable by using the calc() function.

	
		:root {
			--main-top: 10px;
		}

		.negative-margin {
			margin-top: calc(var(---margin-top) * -1);
		}
	

In the above example, we use calc() to multiply the margin, 10px, by -1, which produces a negative var of margin of -10px. This is the easiest way to negate the value of CSS variables.

You May Also Like