offsetWidth and offsetHeight in JavaScript

William Le

Using offsetWidth and offsetHeight in JavaScript, youโ€™re able to get the pixel dimensions of an HTML element. The dimensions are calculated using the dimensions of content inside the HTML element along with any padding, borders, and scrollbars (if present).

๐Ÿ“ The margins of an HTML Element are excluded when computing offsetWidth and offsetHeight

Learn JavaScript basics for free

Using offsetWidth and offsetHeight

<div id="foo">
  Hello World
const offsetWidth = document.querySelector('#foo').offsetWidth;
const offsetHeight = document.querySelector('#foo').offsetHeight;

Learning Exercises

As an exercise, try calculating the value of offsetWidth and offsetHeight of the HTML element below:

offsetwidth offsetheight 1

 **  If the HTML element is <div id="foo"/>  **
const offsetWidth = document.querySelector('div#foo').offsetWidth;
const offsetHeight = document.querySelector('div#foo').offsetHeight;
console.log(offsetWidth, offsetHeight);
// --> 255, 140

How was it calculated? Simply add the border, padding, scrollbar, and the content inside the HTML element (ignore the margins!):

offsetwidth offsetheight 2

Letโ€™s try another! Try calculating the offsetWidth and offsetHeight of this HTML element:

offsetwidth offsetheight 3

offsetWidth === 290
offsetHeight === 160


  • Block-level: offsetWith and offsetHeight does NOT work with inline HTML elements (like span, em, or a). Itโ€™ll just return 0!
  • Rounded Values: Values are rounded to the nearest integer. If you need more precise values use getBoundingoffsetRect()
  • Read-Only: You canโ€™t assign a new value to change the dimensions of the HTML element. For example this doesnโ€™t do anything: someElement.offsetWidth = 30

Browser Compatibility

offsetWidth and offsetHeight are supported on all major desktop and mobile browsers.


Read the official W3C specs for detailed information about offsetWidth and offsetHeight.

offsetWidthCSS Object Model (CSSOM) View ModuleWorking Draft
offsetHeightCSS Object Model (CSSOM) View ModuleWorking Draft
  Tweet It

๐Ÿ•ต Search Results

๐Ÿ”Ž Searching...

Sponsored by #native_company# โ€” Learn More
#native_title# #native_desc#