modern-web-design-and-development

(Brent) #1

Try it yourself to see the results: click here.


3. .css(‘width’) and .css(‘height’) vs. .width() and .height


()


These three, you won’t be shocked to learn, are concerned with calculating
the dimensions of an element in pixels. They both return the offset
dimensions, which are the genuine dimensions of the element no matter
how stretched it is by its inner content.


They differ in the data types they return: css('width') and css
('height') return dimensions as strings, with px appended to the end,
while width() and height() return dimensions as integers.


There’s actually another little-known difference that concerns IE, and it’s
why you should avoid the css('width') and css('height') route. It
has to do with the fact that IE, when asked to read “computed” (i.e. not
implicitly set) dimensions, unhelpfully returns auto. In jQuery core, width
() and height() are based on the .offsetWidth and .offsetHeight
properties resident in every element, which IE does read correctly.


But if you’re working on elements with dimensions implicitly set, you don’t
need to worry about that. So, if you wanted to read the width of one
element and set it on another element, you’d opt for css('width'),
because the value returned comes already appended with ‘px’.


But if you wanted to read an element’s width() with a view to performing
a calculation on it, you’d be interested only in the figure; hence width() is
better.

Free download pdf