Home > Web Front-end > JS Tutorial > How Do I Get the True Width and Height of an HTML Element?

How Do I Get the True Width and Height of an HTML Element?

Mary-Kate Olsen
Release: 2024-12-08 21:57:11
Original
634 people have browsed it

How Do I Get the True Width and Height of an HTML Element?

Determining the Actual Width and Height of an HTML Element

To center an HTML element within the browser's viewport, it is necessary to accurately calculate its dimensions. Here's how to retrieve the actual width and height of an element efficiently.

Using Element Properties

The .offsetWidth and .offsetHeight properties of the HTMLElement interface represent the actual width and height of an element, respectively. Note that these properties are part of the element, not its .style object.

const width = document.getElementById('foo').offsetWidth;
Copy after login

Using getBoundingClientRect()

Alternatively, the getBoundingClientRect() method can be used to obtain the dimensions and location of an element within the viewport as floating-point numbers. This includes the element's position, width, and height after applying CSS transforms.

console.log(document.getElementById('foo').getBoundingClientRect());

// Output:
// DOMRect {
//   ...
//   width: 631,  // Element's width in pixels
//   height: 54.7, // Element's height in pixels
//   ...
// }
Copy after login

Browser Support

Both techniques are supported in modern browsers, including:

  • Chrome
  • Firefox
  • Edge
  • Safari
  • Opera

The above is the detailed content of How Do I Get the True Width and Height of an HTML Element?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template