Using negative CSS Custom Properties

BHOLT picture BHOLT · Mar 24, 2018 · Viewed 8.3k times · Source

In preprocessors, like SASS, you can use negative values like:

$margin-md: 10px;

.class {
  margin-bottom: -$margin-md;
}

How do I do this using custom properties?

// This doesn't work
.class {
  margin-bottom: -var(--margin-md);
}

Answer

BHOLT picture BHOLT · Mar 24, 2018

As of this posting, March 2018, the only way to use negative custom properties is by multiplying it by -1 with the calc function.

// Vanilla CSS
.class {
  margin-bottom: calc(var(--margin-md) * -1);
}

If you're using a preprocessor with custom properties, you'll need to escape the custom property within the calc function.

// SASS
.class {
  margin-bottom: calc(#{var(--margin-md)} * -1);
}