What is the difference between the values returned by .width()
from jQuery, .css('width')
from jQuery, and the .style.width
attribute on a node?
I'm curious because, in trying to set the width of two table cells to be equal, the first two gave me the same wrong answer. What are they actually measuring, and why is it not the same as the value that I can see in the .style
attribute when I view the element in a browser?
From width
official documentation
The difference between .css(width) and .width() 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 .width() method is recommended when an element's width needs to be used in a mathematical calculation.
I'd say there is no difference between .css('width')
and .style.with
as css()
method is used to set style object properties.
The difference between .css('width')
/ .width()
and .style.with
is that jQuery methods get the computed style using window.getComputedStyle( elem, null )
. This method is used to read the actual property after CSS and styles are applied.
Complementing Claudio Redi's answer: see the difference live: http://jsfiddle.net/vovkss/kPXaB/
I've used cm
units intentionally to demonstrate that the output of .css('width')
may be converted to pixels (or other units), while .width()
is always an integer value representing a number of pixels.
Note that .style.width
only applies to inline styles.
HTML:
<div id="mydivInlineStyle" style="width: 10cm"><b>Inline style:</b>
</div>
<div id="mydivExternalStylesheet"><b>External stylesheet:</b>
</div>
CSS:
div {
width: 10cm;
border: 10px solid blue; padding: 11px; margin: 12px;
background: aqua; white-space: pre;
}
JS:
$('div').each(function(){
$(this).append(
'jQuery width(): ' + $(this).width() + "\n" +
'.css(\'width\'): ' + $(this).css('width') + "\n" +
'.style.width: ' + this.style.width
);
});
Output:
Inline style:
jQuery width(): 378
.css('width'): 378px
.style.width: 10cm
External stylesheet:
jQuery width(): 378
.css('width'): 378px
.style.width:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With