instead
instead

Reputation: 3471

Should I add the unit 'px' to numerical values in the css function of jQuery?

Is there any difference between the following?

$(elem).css({ height : 100 })

$(elem).css({ height : 100+'px' })

I've been searching for a long time in Google and I haven't found the answer. On jquery.com there are examples with px and just integer values... Is there some difference in browsers or OS ?

Upvotes: 6

Views: 1288

Answers (1)

Felix Ebert
Felix Ebert

Reputation: 1151

jQuery automatically adds the unit 'px' (as a default unit) to all numbers for the most css properties, including "height":

See line 221 in src/css.js

// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
    value += "px";
}

!jQuery.cssNumber[ origName ] excludes the following css properties:

  • columnCount
  • fillOpacity
  • fontWeight
  • lineHeight
  • opacity
  • orphans
  • widows
  • zIndex
  • zoom

(Side note: If you are like me at first a bit surprised about the exclusion of "lineHeight": a number without a unit will be multiplied with the current font size to set the line height - so there is a difference for the property 'line-height' when you specify / omit the unit)

Upvotes: 8

Related Questions