Read more

Do not use unitless zeros in CSS calc functions

Arne Hartherz
November 14, 2022Software engineer at makandra GmbH

While in CSS zero is usually referenced without specifying a unit (e.g. padding: 0), you must not use a unitless zero in calc functions.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

You would probably not write something like calc(1rem + 0) yourself, but it might be the result of a CSS preprocessor (like Sass) or when using custom properties.

The following is invalid:

.example {
  --extra-padding: 0;
  padding: calc(1rem + var(--extra-padding));
}

That is simply because it is unsupported Show archive.org snapshot , as per documentation:

Because <number-token>s are always interpreted as <number>s or <integer>s, "unitless 0" <length>s aren’t supported in calc(). That is, width: calc(0 + 5px); is invalid, even though both width: 0; and width: 5px; are valid.

An expression with an invalid calc value is ignored, so you might end up with missing or "random" behavior, depending on where you do this.

The above example is valid once you use zero with any allowed unit, e.g.

.example {
  --extra-padding: 0px;
  padding: calc(1rem + var(--extra-padding));
}
Posted by Arne Hartherz to makandra dev (2022-11-14 10:45)