Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
674 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.
...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...