What Is the jQuery cssNumber Object?

The jQuery $.cssNumber object is an internal configuration map that defines which CSS properties can accept raw, unitless numbers without jQuery automatically appending "px" to them. Understanding $.cssNumber is essential for front-end developers who manipulate CSS styles programmatically, as it prevents styling errors caused by unintended pixel units being attached to properties that should remain pure numbers, such as opacity, z-index, or line-height.

How jQuery Handles Numeric CSS Values

When you use jQuery’s .css() method to set a style using a numeric value, jQuery defaults to assuming that the number represents a pixel measurement.

For example:

// jQuery automatically appends "px"
$('#box').css('width', 300); // Result: style="width: 300px;"
$('#box').css('margin-top', 20); // Result: style="margin-top: 20px;"

While this automatic conversion is convenient for dimensional properties like width, height, padding, and top, it breaks properties that do not use pixels. For instance, setting opacity: 1px or z-index: 10px produces invalid CSS.

The Purpose of $.cssNumber

To solve this problem, jQuery references the $.cssNumber object before applying any numeric style. If the property exists in $.cssNumber with a value of true, jQuery leaves the value as a plain number.

Default properties included in $.cssNumber typically include:

  • columnCount
  • fillOpacity
  • flexGrow
  • flexShrink
  • fontWeight
  • lineHeight
  • opacity
  • order
  • orphans
  • widows
  • zIndex
  • zoom

When setting any of these properties, jQuery preserves the raw number:

// Recognized by $.cssNumber: no "px" added
$('#box').css('opacity', 0.5); // Result: style="opacity: 0.5;"
$('#box').css('zIndex', 9999); // Result: style="z-index: 9999;"

Extending the $.cssNumber Object

As modern CSS evolves, new unitless properties are introduced that older versions of jQuery might not include by default. Additionally, you may want to use CSS custom properties (variables) that accept numbers.

You can extend $.cssNumber directly in your JavaScript code:

// Add support for custom properties or new CSS attributes
$.cssNumber.myUnitlessProp = true;
$.cssNumber['--scale-factor'] = true;

// Usage without jQuery appending "px"
$('#box').css('--scale-factor', 2.5);

Summary

The $.cssNumber object acts as an exception list for jQuery's automatic pixel-appending logic. It ensures unitless CSS attributes remain valid numbers when manipulated through the .css() method, and it can be customized whenever support for new unitless properties is required.