Question

How to Get an HTML Element’s Width and Height in JavaScript

htmljavascriptdhtml

Question

How can I determine the width and height of a <div> element in order to center it within the browser viewport? What JavaScript techniques are available for measuring an element’s size, and which browser support considerations apply to each approach?

Short Answer

By the end of this page, you will understand the main ways to measure an HTML element’s width and height in JavaScript, when to use each property or method, and how those measurements affect tasks like centering an element in the viewport. You will also see common pitfalls, browser considerations, and practical examples for real projects.

Concept

Measuring an element’s size is a core part of DOM programming in JavaScript. When you want to center a popup, position a tooltip, animate layout, or respond to resizing, you often need the element’s actual rendered dimensions.

In the browser, an element can have several different “sizes” depending on what you mean:

  • Content size: just the inner content area
  • Client size: content + padding
  • Offset size: content + padding + border
  • Rendered rectangle: the element’s size and position as currently drawn on screen

Common APIs include:

  • element.offsetWidth and element.offsetHeight
  • element.clientWidth and element.clientHeight
  • element.getBoundingClientRect()
  • window.getComputedStyle(element) for reading CSS values

These matter because two widths that sound similar may produce different numbers. For example, if an element has padding and borders, clientWidth and offsetWidth will not match.

For centering, the most useful modern measurement is often getBoundingClientRect(), because it reflects the element’s rendered box. But offsetWidth and offsetHeight are also simple and widely used.

A key detail: if an element is hidden with display: none, many size properties return 0 because the browser is not rendering it in the layout.

Mental Model

Think of an HTML element like a framed picture on a wall:

  • The content is the image itself.
  • The padding is the empty space around the image.
  • The border is the frame.
  • The margin is the space between the picture frame and nearby pictures.

Different JavaScript properties measure different parts of that picture.

  • clientWidth measures the image plus the empty space inside the frame.
  • offsetWidth measures the image, the inner space, and the frame.
  • getBoundingClientRect() measures the whole visible rectangle on the wall exactly as it appears.

So before measuring, ask: Which box do I actually need?

Take Quiz

Syntax and Examples

The most common ways to measure a DOM element are shown below.

1. offsetWidth and offsetHeight

These include:

  • content
  • padding
  • border

They do not include margins.

const box = document.getElementById('box');

console.log(box.offsetWidth);
console.log(box.offsetHeight);

This is a simple choice when you want the element’s visible layout size.

2. clientWidth and clientHeight

These include:

  • content
  • padding

They do not include:

  • border
  • margin
const box = document.getElementById('box');

console.log(box.clientWidth);
console.log(box.clientHeight);

Use this when borders should not count.

3. getBoundingClientRect()

This returns a rectangle object with size and position.

const box = document.getElementById('box');
const rect = box.getBoundingClientRect();

console.log(rect.width);
console.log(rect.height);
console.log(rect.left);
console.log(rect.top);

This is especially useful for positioning elements relative to the viewport.

4. getComputedStyle()

This reads CSS values as strings.

const box = document.getElementById('box');
const styles = window.getComputedStyle(box);

console.log(styles.width);   // e.g. "200px"
console.log(styles.height);  // e.g. "100px"

If you need numbers, convert them:

const width = parseFloat(styles.width);
const height = parseFloat(styles.height);

Be careful: computed style values depend on CSS rules and box-sizing, so they may not match the layout measurement you expect.

Example: center a <div> in the viewport

<div id="modal">Hello</div>
#modal {
  position: fixed;
  padding: 20px;
  border: 2px solid black;
  background: white;
}
const modal = document.getElementById('modal');
const rect = modal.getBoundingClientRect();

const left = (window.innerWidth - rect.width) / 2;
const top = (window.innerHeight - rect.height) / 2;

modal.style.left = `${left}px`;
modal.style.top = `${top}px`;

This places the element in the center of the viewport based on its rendered size.

Step by Step Execution

Consider this example:

<div id="dialog">Centered box</div>
#dialog {
  position: fixed;
  width: 300px;
  padding: 20px;
  border: 4px solid black;
}
const dialog = document.getElementById('dialog');
const rect = dialog.getBoundingClientRect();

const x = (window.innerWidth - rect.width) / 2;
const y = (window.innerHeight - rect.height) / 2;

dialog.style.left = `${x}px`;
dialog.style.top = `${y}px`;

Here is what happens step by step:

  1. document.getElementById('dialog') finds the element.
  2. dialog.getBoundingClientRect() asks the browser for the element’s current rendered rectangle.
  3. rect.width gives the actual displayed width.
  4. rect.height gives the actual displayed height.
  5. window.innerWidth gives the viewport width.
  6. window.innerHeight gives the viewport height.
  7. Subtracting the element size from the viewport size gives the remaining space.
  8. Dividing by 2 places half that remaining space on each side, which centers the element.
  9. Assigning left and top positions moves the fixed element into place.

If the dialog width is 348px after padding and border are included, and the viewport width is 1200px, then:

x = (1200 - 348) / 2; // 426

So the element is placed 426px from the left edge.

Real World Use Cases

Measuring element dimensions is common in many real applications.

Popups and modals

A modal dialog may need to be centered on screen after its content loads.

Tooltips and dropdowns

You often measure a button and a tooltip to position the tooltip above, below, or beside the button.

Drag-and-drop interfaces

Apps measure card, list, or container dimensions to detect overlap and drop zones.

Responsive UI adjustments

A script may reduce font size, switch layout, or reposition elements based on available space.

Virtualized lists and grids

Large apps measure row heights or card widths to render only visible items efficiently.

Canvas and media overlays

When drawing annotations over images or videos, the script may match overlay dimensions to the rendered element.

Take Quiz

Real Codebase Usage

In real projects, developers usually do more than just read width and height once.

Common patterns

Guard clauses

Check that the element exists before measuring it.

const box = document.getElementById('box');
if (!box) return;

Measure after rendering

If content is loaded dynamically, measure only after the element is in the DOM and visible.

requestAnimationFrame(() => {
  const rect = box.getBoundingClientRect();
  console.log(rect.width, rect.height);
});

Recalculate on resize

If the viewport changes, centered positions may need updating.

function centerElement(el) {
  const rect = el.getBoundingClientRect();
  el.style.left = `${(window.innerWidth - rect.width) / 2}px`;
  el.style.top = `${(window.innerHeight - rect.height) / 2}px`;
}

window.addEventListener('resize', () => centerElement(modal));

Validate hidden-state assumptions

If an element is hidden with display: none, measurements may be zero.

Prefer CSS when possible

For simple centering, CSS is often cleaner than JavaScript.

.modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

That avoids manual width and height calculations entirely.

Modern project usage

In production code, developers frequently combine:

  • getBoundingClientRect() for accurate positioning
  • ResizeObserver for reacting to element size changes
  • CSS transforms for centering
  • event listeners for viewport resizing

Common Mistakes

Here are common mistakes beginners make when measuring element size.

1. Confusing width with rendered width

Broken example:

const styles = getComputedStyle(box);
console.log(styles.width);

Why this can be misleading:

  • It returns a string like "200px"
  • It may reflect CSS sizing rules rather than the box you want
  • box-sizing changes what that width means

Better:

console.log(box.offsetWidth);

2. Measuring an element before it exists

Broken example:

const box = document.getElementById('box');
console.log(box.offsetWidth);

If the script runs before the element is parsed, box is null.

Better:

document.addEventListener('DOMContentLoaded', () => {
  const box = document.getElementById('box');
  console.log(box.offsetWidth);
});

3. Measuring hidden elements

Broken example:

box.style.display = 'none';
console.log(box.offsetWidth); // 0

If an element is not rendered, the browser cannot give a visible size.

4. Forgetting borders and padding

Broken assumption:

if (box.clientWidth === box.offsetWidth) {
  console.log('Same size');
}

These are only equal when border sizes do not affect the difference.

5. Ignoring scrolling and viewport positioning

getBoundingClientRect() returns values relative to the viewport, not the full document.

If you need document coordinates, add scroll values:

const rect = box.getBoundingClientRect();
const documentLeft = rect.left + window.scrollX;
const documentTop = rect.top + window.scrollY;

6. Using JavaScript when CSS already solves the problem

For basic centering, CSS is often simpler, more maintainable, and less error-prone.

Comparisons

Here is a practical comparison of the main measurement techniques.

TechniqueIncludes PaddingIncludes BorderIncludes MarginReturns Number or StringBest Use
element.clientWidth / clientHeightYesNoNoNumberInner box size
element.offsetWidth / offsetHeightYesYesNoNumberLayout size including border
element.getBoundingClientRect()YesYesNoNumber values inside objectAccurate rendered size and position
getComputedStyle(element).widthDepends on CSSDepends on box-sizingNoString like "200px"Reading computed CSS

Which one should you use?

  • Use offsetWidth / offsetHeight for simple layout measurements.
  • Use clientWidth / clientHeight when borders should not count.
  • Use getBoundingClientRect() when you need both size and position in the viewport.
  • Use getComputedStyle() when you specifically need CSS values, not just rendered measurements.

Browser support

These APIs are broadly supported in modern browsers.

  • offsetWidth, offsetHeight, clientWidth, and clientHeight have long-standing support across browsers.
  • getBoundingClientRect() is also widely supported and is the standard choice in modern DOM code.
  • getComputedStyle() is supported in modern browsers; very old legacy browsers had quirks or alternative APIs.

For modern web development, all of these are considered safe to use. If you are targeting very old browsers, test exact behavior carefully.

Take Quiz

Cheat Sheet

// Includes padding + border
el.offsetWidth;
el.offsetHeight;

// Includes padding, excludes border
el.clientWidth;
el.clientHeight;

// Includes size + position relative to viewport
const rect = el.getBoundingClientRect();
rect.width;
rect.height;
rect.left;
rect.top;

// Reads computed CSS values as strings
const styles = getComputedStyle(el);
styles.width;
styles.height;
parseFloat(styles.width);

Quick rules

  • offsetWidth = content + padding + border
  • clientWidth = content + padding
  • Margins are not included in these properties
  • getBoundingClientRect() gives viewport-relative position and size
  • Hidden elements with display: none often measure as 0
  • getComputedStyle() returns strings, not numbers
  • For simple centering, CSS transform: translate(-50%, -50%) is often easier

Centering formula

const rect = el.getBoundingClientRect();
const left = (window.innerWidth - rect.width) / 2;
const top = (window.innerHeight - rect.height) / 2;

Preferred choices

  • Need quick size: offsetWidth
  • Need inner size: clientWidth
  • Need size + position: getBoundingClientRect()

FAQ

How do I get the actual width and height of a div in JavaScript?

Use offsetWidth and offsetHeight for a simple layout measurement, or getBoundingClientRect() for accurate rendered size and position.

What is the difference between clientWidth and offsetWidth?

clientWidth includes content and padding. offsetWidth includes content, padding, and border.

Does getBoundingClientRect() include borders?

Yes, it reflects the rendered border box of the element.

Why is my element width returning 0?

The element may be hidden with display: none, not yet added to the DOM, or measured before rendering is complete.

Can I use CSS instead of JavaScript to center an element?

Yes. In many cases, CSS is better:

position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

Is getComputedStyle().width the same as offsetWidth?

No. getComputedStyle().width returns a CSS value as a string and may differ depending on box-sizing and layout rules.

Which method is best for browser compatibility?

offsetWidth, clientWidth, and getBoundingClientRect() are all well supported in modern browsers. For current web development, they are standard and safe choices.

Take Quiz

Mini Project

Description

Build a small modal-style panel that appears centered in the viewport using JavaScript measurements. This project demonstrates how to read an element’s rendered dimensions and place it correctly, even when the browser window is resized.

Goal

Create a centered dialog box by measuring its size with JavaScript and updating its position based on the viewport.

Requirements

  • Create a dialog <div> with visible content, padding, and a border.
  • Measure the dialog’s rendered width and height in JavaScript.
  • Center the dialog in the viewport using calculated left and top values.
  • Re-center the dialog when the browser window is resized.
  • Keep the dialog visible using CSS positioning.
Take Quiz

Keep learning

Related questions

View more