Do not use unitless zeros in CSS calc functions

Posted . Visible to the public.

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.

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));
}
Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2022-11-14 09:45)