Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
92
rated 0 times [  94] [ 2]  / answers: 1 / hits: 40149  / 9 Years ago, mon, september 7, 2015, 12:00:00

In MDN's description of Element.clientWidth it says.




Note: I've since updated MDN according to @potatopeelings answer.




The Element.clientWidth property is the inner width of an element in pixels. It includes padding but not the vertical scrollbar (if present, if rendered), border or margin.




This property will round the value to an integer. If you need a fractional value, use element.getBoundingClientRect().





From this I understand that other than rounding clientWidth should be the same as getBoundingClientRect().width.



However I see that for many elements (where display is inline?) the clientWidth (and height) are zero, while the values returned by getBoundingClientRect seem correct.



Searching on stackoverflow brings some answers saying that this happens before the document is in a ready state but I see this all the time, not just when the page is loading.



This behaviour is consistent for all browsers I checked, where is it specified that this should be the behaviour?



Sample:



function str(name, width, height) {
return name + ': (' + width + ', ' + height + ')';
}

function test() {
var s = document.getElementById('s');
var rect = s.getBoundingClientRect();
document.getElementById('out').innerHTML =
str('client', s.clientWidth, s.clientHeight) + '<br/>' +
str('bounding', rect.width, rect.height);
}

 <span id=s>A span</span><br/> <button onclick=test()>Test</button>
<hr />
<div id=out></div>




More From » html

 Answers
8

From the spec (http://www.w3.org/TR/cssom-view/#dom-element-clientwidth)




The clientWidth attribute must run these steps:



1.If the element has no associated CSS layout box or if the CSS layout box is inline, return zero.

...



[#65159] Friday, September 4, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
demondp

Total Points: 154
Total Questions: 97
Total Answers: 99

Location: Mali
Member since Thu, Jul 9, 2020
4 Years ago
;