DEV Community

loading...
Cover image for Simple way to negate a number in CSS

Simple way to negate a number in CSS

Dzhavat Ushev
Front-end developer trying to make useful stuff.
Originally published at dzhavat.github.io ・1 min read

This post was originally published on my blog.


I was experimenting with Custom properties a.k.a CSS variables last night. I was trying to create a simple card design for fun to see how things work. At one point I wanted to negate a variable that held a positive number.

My first attempt was:

:root {
  --base-padding: 1rem;
}

.card-image {
  margin: -var(--base-padding);
}

Nice try, weirdo, but this doesn’t work! Come up with something smarter. 😝

Well, the “trick” was to use the calc() function and multiply the value of the variable by -1.

:root {
  --base-padding: 1rem;
}

.card-image {
  margin: calc(var(--base-padding) * -1);
  /* results to margin: -1rem */
}

This is actually not a “trick” at all. It’s how math works. Hurray for math! 🎉

The same technique works the other way around as well - converting a negative number to a positive one.

:root {
  --base-top-position: -1rem;
}

.card-image {
  top: calc(var(--base-top-position) * -1);
  /* results to top: 1rem */
}

Is there another way to negate numbers in CSS? Let me know in the comments below.

Hope you learned something new.

Oh, and if you’re curious how I used that in my card design...

Discussion (2)

Collapse
alohci profile image
Nicholas Stimpson

You could subtract from 0px too, like this:

margin: calc(0px - var(--base-padding));
Collapse
dzhavat profile image
Dzhavat Ushev Author

That's great! Thanks for sharing it. We can even save 2 characters by removing the px. It's not really needed :)