Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

integer

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 ?

like image 244
instead Avatar asked Apr 01 '13 16:04

instead


People also ask

Can we change CSS properties values using JavaScript or jQuery?

CSS variables have access to the DOM, which means that you can change them with JavaScript.

What is PX JavaScript?

Px. js is a JavaScript library for extracting and manipulating data stored in PC-Axis files. It is intended as a generic solution which can handle any well-formed PC-Axis file. Px. js is primarily intended for use in a web browser but it can also be used as a Node.

How to set style property in jQuery?

Set a Single CSS Property and Value The css() method can take a property name and value as separate parameters for setting a single CSS property for the elements. The basic syntax can be given with: $(selector). css("propertyName", "value");

Why this is used in jQuery?

The this Keyword is a reference to DOM elements of invocation. We can call all DOM methods on it. $() is a jQuery constructor and in $(this), we are just passing this as a parameter so that we can use the jQuery function and methods.


1 Answers

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)

like image 77
Felix Ebert Avatar answered Nov 03 '22 10:11

Felix Ebert