23

Guys I've been asking around and nobody can really tell me the benefits of using .css(‘width’) and .css(‘height’) rather than .width() and .height().

I know that they both return the offset dimensions, which are the genuine dimensions of the element no matter how stretched it is by its inner content.

I'm guessing that there are some things that one can do and the other one cannot as I was using css() to return the dimensions of a window and document, where FF had no issues doing this but IE threw back an error at me. So I'm guessing that they might work in some browsers and but others. So would I have to use both together for 100% cross browser compatibility or just for certain cases?

fzzle
  • 1,466
  • 5
  • 23
  • 28
Epik
  • 3,327
  • 4
  • 17
  • 23
  • 5
    `.css('width')` returns the value with units (`5px`). `.width()` returns the width in pixels as a number. – Blender Nov 07 '12 at 22:44
  • 1
    A very nice post about this and something else: http://blog.jquery.com/2012/08/16/jquery-1-8-box-sizing-width-csswidth-and-outerwidth/ – Robyflc Nov 07 '12 at 22:47

10 Answers10

16

From the .height() documentation -

The difference between .css('height') and .height() is that the latter returns a unit-less pixel value (for example, 400) while the former returns a value with units intact (for example, 400px). The .height() method is recommended when an element's height needs to be used in a mathematical calculation.

If you need to use height in a calculation get the value with .height().

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • 3
    you missed a very important fact, that in some cases .css("height"); returns something else than .height(); does – Xatenev Sep 15 '15 at 11:03
  • 3
    That is *exactly* what the docs say @Xatenev, they return two different things. – Jay Blanchard Sep 15 '15 at 11:41
  • 6
    Well actually I meant it differently sorry. .height() always returns the computed height. Means if you have a div with no content in it it will return 0 but .css("height") will return the height you set for the div in your CSS, for example 300px. In my opinion thats quite an important fact which sometimes leads to weird "issues". – Xatenev Sep 15 '15 at 13:06
  • That is why the docs say, *"he .height() method is recommended when an element's height needs to be used in a mathematical calculation."* @Xatenev Are you saying I should clarify that point? – Jay Blanchard Sep 15 '15 at 13:20
  • Basically yeah, just 2 hours ago somebody had exactly the problem I described in IRC #jquery. He came across this stackoverflow thread and couldn't find a solution here. – Xatenev Sep 15 '15 at 13:24
  • Out of all of the solutions in this thread he could not find a solution @Xatenev? I find that hard to believe. – Jay Blanchard Sep 15 '15 at 13:24
  • Ay, just sayin that there is only one sentence in the doc which explains the problem with the computed height/width. you dont have to extend your answer if you think different here :) #end – Xatenev Sep 15 '15 at 13:28
  • I don't know if I can say it any clearer than the documents do. ¯\\_(ツ)_/¯ – Jay Blanchard Sep 15 '15 at 13:29
10

Guys ive been asking around and no one can really tell me the benefits of using .css(‘width’) and .css(‘height’)rather then .width() and .height().

Querying CSS will give you the applied value as in 5px or 1em or what ever size is assigned to it.

Using jQuery you can use the following methods:

  • .height (element height, without padding , margins or borders)
  • .innerHeight (element height + padding)
  • .outerHeight (element height + padding and borders)
  • .outerHeight(true) (element height + padding + borders + margin)
  • .width (element width, without padding , margins or borders)
  • .innerWidth (element width + padding)
  • .outerWidth (element width + padding and borders)
  • .outerWidth(true) (element width + padding + borders + margin)

All of those methods will return just a number, representing the height/width units in pixels.

The benefit using jQuery is across browser you are able to be more in control of the exact width/height by being able to ignore/include margins, paddings or borders.

Furthermore, as those methods always return the units as a plain number it is easier to calculate with them as previously mentioned as you don't need to worry about the measurement itself, i.e: px, em, etc..

DEMO - Demonstrating height methods (same applies to width)

The demo above is using a div:

<div id="myDiv">My Div</div>

With the following CSS:

div{
    border: 1px solid blue;
    padding: 5px;
    margin: 10px;
}

Using this script:

var $div = $("#myDiv");
var height = $div.height();
var heightWithPadding = $div.innerHeight();
var heightWithPaddingAndBorder = $div.outerHeight();
var heightWithPaddingAndBorderAndMargin = $div.outerHeight(true);

var $result = $("#result");
$result.append("height: " + height);
$result.append("<br />height with padding: " + heightWithPadding);
$result.append("<br />height with padding and borders: " + heightWithPaddingAndBorder);
$result.append("<br />height with padding and borders and margin: " + heightWithPaddingAndBorderAndMargin);

Resulting in the following:

height: 20
height with padding: 30
height with padding and borders: 32
height with padding and borders and margin: 52
Nope
  • 22,147
  • 7
  • 47
  • 72
  • @roXon: I thought the question was what the benefit was using one over the other. I thought that was self-explanatory. I have added an additional quote that the benefit in using jquery's methods was the ability of finer control, being able to include/exclude margin, paddings and border units as required. I assume that it is a benefit. Then again, I know you can do all that just in plain CSS. Apologies if I misunderstood the question though. – Nope Nov 07 '12 at 23:12
  • Your answer is actually really great, +1 just add the $().css('property') example. – Roko C. Buljan Nov 07 '12 at 23:13
  • 1
    @roXon: I also mentioned what you said about calculating values. +1 for that as I completely missed that originally. Feel free to edit my post if you feel it should mentioned anything else. – Nope Nov 07 '12 at 23:17
  • "Querying CSS will give you the applied value as in 5px or 1em..." Apparently not. .css('width') **always returns a string ending in `px`** even if set in other units. [jQuery says](http://api.jquery.com/css/): "...computed styles of dimensions are almost always pixels..." (Not sure what "almost" means.) – Bob Stein Jun 22 '17 at 15:47
7
var elH = someElement.height();           // 200

.height() returns a Number, while

var elH = someElement.css("height");      // "200px"

above jQuery accesses the element's style property like JS would in:

var height = someDOMelement.style.height; // "200px"

returning a String value in px.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • 3
    you missed a very important fact, that in some cases .css("height"); returns something else than .height(); does – Xatenev Sep 15 '15 at 11:03
  • 2
    @Xatenev No he didn't, he put what it returns in the code comment. – Jamie Barker Sep 15 '15 at 11:49
  • 1
    I have a case where I have set a DIV height to 50px. .height() returns 39 while .css("height") returns 50px. I don't know why but in this case I rather trust .css("height") – Jonny Jun 28 '18 at 19:28
2

they will also return/set different values (not talking about the 'px' suffix)

if you have box-sizing: border-box

see this example: http://jsbin.com/fugusixila/edit?html,css,js,console,output

Omu
  • 69,856
  • 92
  • 277
  • 407
1

I have provided this answer because the question was asking about things you can do with css() and not width() and vice versa. There is an interesting case for page elements which are hidden.

I had a situation recently where I needed to move some elements dynamically that were sometimes hidden, sometimes not when the page loaded. When the elements were not hidden, it was easy to just use the elements actual width to create the new DOM structure. But when the elements are hidden, using .width() returned 0, and rightly so. So I needed to add some CSS width info to the elements class and from that I was able to create a statement like

var width = $('#element').width() == 0 ? parseInt($('#element').css('width')) : $('#element').width();

This enabled me to ensure I was using the width when it was available, but also providing a fallback value for when the element was hidden.

Hopefully this adds to the understanding of the difference between what you can do with these two methods.

samazi
  • 1,161
  • 12
  • 24
0

.width returns a unitless value, where as .css("width") returns the css value, width should be used with mathematical calculations

http://api.jquery.com/width/

mikeswright49
  • 3,381
  • 19
  • 22
0

Yeap!
Main thing is, as most everyone told ".height() returns a unit-less pixel value".

But the question remains: Why is this so...?... Why was this thought this way?


@Jay Blanchard well said it: "The .height() method is recommended when an element's height needs to be used in a mathematical calculation."

So, if I may added, use "CSS" dim's everytime you deal with native stand-alone browser reactions - very handy to compute/react to elements disposition on a responsive window/div re-dimension process.

Use width() / height() to compute JQuery effect results, like hide()/show() inner layers (as you know won't affect CSS height).
Note also that CSS height property, for instance, does not include padding, border, or margin (you don't have inner X / outer X CSS dim's). So these must be computed.

Take a look at jQuery: Get height of hidden element in jQuery

Community
  • 1
  • 1
Pedro Ferreira
  • 493
  • 7
  • 14
0

By now people should know that one should be used for maths, and the other shouldn't...

Or should it?

I did a little speed test on the various options and according to my findings:

  1. It is faster to grab the width with .css
  2. It is faster to set the width with .width

So in other words, to do a grab something and set another, you probably should:

$('#element1').width(parseInt($('#element2').css('width'), 10));
Jamie Barker
  • 8,145
  • 3
  • 29
  • 64
  • `.css('width')` and `.width()` return something different in **every** case. `.css` returns a string and `.width` returns an integer. Hence using `parseInt` on `.css` to return the same as what `.width` on it's own returns. So I'm afraid it's your understanding that's wrong, not the answer. I see you put the same comment on two other answers that even specifically show this information, so I'm guessing you're just a troll. – Jamie Barker Sep 15 '15 at 11:51
  • Check my comment @ Jay Blanchards post. Thanks – Xatenev Sep 15 '15 at 13:06
0

".height() will always return the content height, regardless of the value of the CSS box-sizing property. As of jQuery 1.8, this may require retrieving the CSS height plus box-sizing property and then subtracting any potential border and padding on each element when the element has box-sizing: border-box. To avoid this penalty, use .css( "height" ) rather than .height()"

http://api.jquery.com/height/

Chưa biết
  • 919
  • 8
  • 6
0

Since this was the first hit in google when I was trying to remember the difference between the two, I thought I'd give a little more explanation with an example.

I have a div called myDiv like this:

border:1px solid black;
padding-right: 15px;
padding-left:15px;
margin-right:10px;
margin-left:10px

Console gives me this:

$('#myDiv').css('width') = 1100px;
$('#myDiv').width() = 1068;

1100 includes the 15 pixels for the right padding, the 15 pixels for the left padding, 2 pixels for the border(1 for each side) but NOT the margins. At least for me in chrome. 1068+15+15+1+1 = 1100

Yes, there is overhead for doing Number($('#myDiv').css('width').replace('px', '')) but you only have to do it once each time. And you do have to cast the result as a Number, assuming that you want Number($('#myDiv').css('width').replace('px', '')) + 99 to be 1199. Otherwise you get 110099 as the answer.

Bob Ramsey
  • 95
  • 1
  • 9
  • have not tested this in a while but regarding the casting part, I do believe *parseInt(string)* function will work without having to **.replace('px', '')**; like this: `parseInt($('#myDiv').css('width'))`, returning a number – Scaramouche Feb 15 '18 at 19:26