CSS Custom Properties Negation with Calc()

Convert CSS custom properties between positive and negative values using calc() for dynamic spacing and positioning.

Explanation

  • calc(var(--property) * -1): Converts any positive custom property value to negative.
  • calc(var(--property) * -1): Also converts negative values back to positive (double negative).
  • Enables dynamic sign flipping without defining duplicate variables.
  • Works with any unit type (px, rem, em, %, etc.) defined in the custom property.

Usage

To convert custom properties between positive and negative values:

:root {
  --space-1: 0.25rem;
  --space-2: 0.5rem;
  --space-4: 1rem;
  --space-8: 2rem;
  --margin-large: 2rem;
  --margin-large-negative: calc(var(--margin-large) * -1);
}

/* Negative margins using calc() */
.component {
  margin-top: calc(var(--space-4) * -1);
  margin-bottom: calc(var(--space-2) * -1);
}

/* Transform translations */
.slide-left {
  transform: translateX(calc(var(--space-8) * -1));
}

.slide-right {
  transform: translateX(var(--space-8));
}

/* Dynamic positioning */
.card {
  top: calc(var(--space-4) * -1);
  left: calc(var(--space-2) * -1);
}

/* Converting negative back to positive */
.negative-to-positive {
  /* If --negative-value is -1rem, this becomes 1rem */
  margin: calc(var(--negative-value) * -1);
}

Benefits

  • DRY Principle: Define spacing values once, use them positively or negatively
  • Dynamic: Sign can be flipped at runtime using calc()
  • Consistent: Maintains unit consistency across the design system
  • Flexible: Works with any numeric value including fractions and decimals