How jQuery css() Handles Hyphenated Properties

When passing a style object to jQuery's .css() method, developers can use either traditional hyphenated CSS property names or their camelCase equivalents. jQuery automatically normalizes hyphenated string keys into camelCase internally before applying them to the DOM element's style properties, ensuring that both notations produce identical rendering across all modern browsers.

Internal Normalization Process

Browsers expose inline styling on DOM elements through the JavaScript element.style interface, which expects camelCase property names (such as style.backgroundColor instead of style.background-color).

When an object is passed to jQuery's .css() method, jQuery iterates over each key-value pair. If it encounters a key containing a hyphen, jQuery uses an internal utility function to convert the hyphenated string into camelCase (e.g., converting font-size to fontSize). Once converted, jQuery applies the value directly to the element's style declaration or handles any browser-specific fallbacks.

JavaScript Object Syntax Requirements

While jQuery supports both conventions, the JavaScript language imposes strict rules regarding how object keys are defined:

  • Hyphenated Properties: Must be wrapped in single or double quotes. Without quotes, the JavaScript interpreter reads the hyphen as an arithmetic subtraction operator, resulting in a syntax error.
  • CamelCase Properties: Can be written as unquoted identifier names or wrapped in quotes.
// Valid: Hyphenated properties wrapped in quotes
$('#element').css({
  'background-color': '#f0f0f0',
  'border-top-width': '2px',
  'font-size': '16px'
});

// Valid: CamelCase properties without quotes
$('#element').css({
  backgroundColor: '#f0f0f0',
  borderTopWidth: '2px',
  fontSize: '16px'
});

Both code blocks yield the exact same inline style attributes on the target element.

Vendor Prefixes

jQuery also handles vendor-prefixed properties formatted with hyphens, such as -webkit- or -moz-. When providing properties like '-webkit-border-radius', wrapping the string in quotes ensures jQuery correctly parses the leading hyphen and camelCases the remainder into WebkitBorderRadius, matching standard browser implementation rules.

Performance and Best Practices

While using camelCase allows jQuery to bypass the minor internal string transformation, the performance difference is negligible in real-world scenarios. Choosing between hyphenated or camelCase syntax typically comes down to code consistency and style guides: camelCase aligns closely with native JavaScript DOM scripting, whereas quoted hyphenated strings mirror standard CSS stylesheets.