Go back

Infinity in CSS

Practical CSS infinity techniques for rounded corners, z-index, Boolean logic, backgrounds, animations and one-sided clamp.

Infinity in CSS

Adam Argyle has published a great breakdown on nerdy.dev of practical uses for the infinity and -infinity keywords inside CSS math functions (calc(), clamp(), min(), max()).

The main syntax rule: infinity is a unitless number. You cannot set border-radius: infinity, but you can multiply it by any units inside calc():

  • Perfect pills and rounded corners: border-radius: calc(infinity * 1px) No more magic with arbitrary 9999px. The browser clamps the value to half the element’s smallest dimension.
  • The absolute maximum for z-index: z-index: calc(infinity) A guaranteed way to move an element to the very top of its stacking context, without guessing whether someone will beat your z-index: 999999.
  • Boolean logic right in CSS: The neatest trick is combining infinity and clamp(). You can enable and disable properties without JS or media queries: border-radius: clamp(0px, (100cqi - 100%) * infinity, 20px); How it works: if 100cqi is greater than 100%, the expression produces a positive number; multiplying it by infinity hits the clamp “ceiling” (returning 20px). As soon as the condition becomes negative, the result is -infinity and clamp resets the value to 0px.
  • An unbounded background without absolute positioning: box-shadow: 0 0 0 calc(infinity * 1px) #0005 An instant overlay/backdrop in every direction without calculating the viewport width.
  • Freezing animations and View Transitions: animation-duration: calc(infinity * 1s) freezes the frame completely, which is extremely handy for debugging complex View Transition states directly in DevTools.
  • One-sided clamp(): If you needed to bound a value only below or only above, it used to take some fiddling. Now you can simply pass -infinity as the lower threshold.

Read the post

What do you think of this native replacement for 9999px hacks? Are you already using infinity in production, or is the old habit of hammering out “nines” on the keyboard still stronger?

Copied