JS: Find Element Width

By Xah Lee. Date: . Last updated: .
e.offsetWidth
  • The visible width of element e.
  • By default, it includes padding, border, but not margin.
  • Does not consider 2D Transform.
e.clientWidth

width, includes padding, but not border nor margin.

e.getBoundingClientRect().width

Return the rendered width of the bounding box. For example, it takes consideration when 2D transform is used to scale the element.

Example

XYZ
<div id="box63800">
XYZ
</div>
#box63800 {
width: 100px;
padding: 3px;
border: solid 5px red;
margin: 7px;
box-sizing: content-box;
}

Here is the JavaScript code

// 2018-08-08
// show several js/dom width values of eleId, show them at anchorId
const displayIt = ((eleId, anchorId) => {
    const xx = document.getElementById (eleId);
    const anchor = document.getElementById (anchorId);
    anchor.innerHTML = `<ul>
<li>offsetWidth」 is ${xx.offsetWidth}</li>
<li>clientWidth」 is ${xx.clientWidth}</li>
<li>getBoundingClientRect().width」 is ${xx.getBoundingClientRect().width}</li>
</ul>`;
});

displayIt("box39721", "anchor2_90388");

Example with box-sizing border-box

〔see CSS: Box Sizing

XYZ
<div id="box39721">
XYZ
</div>
#box39721 {
width: 100px;
padding: 3px;
border: solid 5px red;
margin: 7px;
box-sizing: border-box;
}

Example with 2D Transform

〔see CSS: Transform

XYZ
<div id="transf29881">
XYZ
</div>
#transf29881 {
width: 100px;
padding: 3px;
border: solid 5px red;
margin: 7px;
box-sizing: content-box;
transform:rotate(18deg);
}