In this section, we will learn what the Element offsetWidth property is and how to use it in JavaScript.
What is Element offsetWidth Property in JavaScript?
The JavaScript Element offsetWidth property is used to get the “viewable” width of an element in pixels.
This width included the size of the content and padding and border, as well as the vertical scroll-bar if present. But not the margin of the element.
Notes:
- We say “viewable” width of an element. That means if the target element has a fixed width but there was an overflow of content, then the width would be only the value set for the `width` property (which is the visible width of the element) + the size of the padding and border.
- Check the CSS Box Model section if you’re not familiar with it.
JavaScript offsetWidth Property Syntax:
element.offsetWidth;
JavaScript offsetWidth Property Input Value
The offsetWidth property is read-only and so we can’t assign a value to it.
JavaScript offsetWidth Property Return Value
The return value of this property, as mentioned before, is the viewable width of the element.
Example: using offsetWidth Property in JavaScript
See the Pen using offsetWidth Property in JavaScript by Omid Dehghan (@odchan1) on CodePen.
How does Element offsetWidth property work in JavaScript?
Here the width of the <ol> element is set to 100px, the padding is set to 20px and the border to 10px.
So that’s how the offsetWidth returned the value 160px:
100px + 20px + 20px + 10px + 10px = 160px