JS: Find Element Width

By Xah Lee. Date: . Last updated: .

There are 3 properties you can use to find the width or height of a element, depending on exactly what you mean by width.

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 → returns the rendered width of the bounding box. For example, it takes consideration when 2D transform is used to scale the element.

[see CSS: Margin vs Padding]

[see CSS: 2D Transform]

Example

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

Here's 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>offsetWidthis ${xx.offsetWidth}</li>
<li>clientWidthis ${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: 2D 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);
}

Find Element/Viewport/Window Size

  1. CSS: Fixed Aspect Ratio
  2. JS: Find element Size
  3. JS: Find Window Size
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS Basics
  4. JS in Depth
  5. JS Reference
  6. DOM
  7. SVG
  8. JS Misc