Dzhavat Ushev

Twitter GitHub RSS

Simple way to negate a number in CSS

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 on Twitter.

Hope you learned something new.

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

See the Pen Convert positive to negative number by Dzhavat (@dzhavat) on CodePen.

Share on Twitter