[javascript] How do I retrieve an HTML element's actual width and height?

Suppose that I have a <div> that I wish to center in the browser's display (viewport). To do so, I need to calculate the width and height of the <div> element.

What should I use? Please include information on browser compatibility.

This question is related to javascript html dhtml

The answer is


You only need to calculate it for IE7 and older (and only if your content doesn't have fixed size). I suggest using HTML conditional comments to limit hack to old IEs that don't support CSS2. For all other browsers use this:

<style type="text/css">
    html,body {display:table; height:100%;width:100%;margin:0;padding:0;}
    body {display:table-cell; vertical-align:middle;}
    div {display:table; margin:0 auto; background:red;}
</style>
<body><div>test<br>test</div></body>

This is the perfect solution. It centers <div> of any size, and shrink-wraps it to size of its content.


If offsetWidth returns 0, you can get element's style width property and search it for a number. "100px" -> 100

/\d*/.exec(MyElement.style.width)


element.offsetWidth and element.offsetHeight should do, as suggested in previous post.

However, if you just want to center the content, there is a better way of doing so. Assuming you use xhtml strict DOCTYPE. set the margin:0,auto property and required width in px to the body tag. The content gets center aligned to the page.


... seems CSS help to put div on center ...

<style>
 .monitor {
 position:fixed;/* ... absolute possible if on :root */
 top:0;bottom:0;right:0;left:0;
 visibility:hidden;
 }
 .wrapper {
 width:200px;/* this is size range */
 height:100px;
 position:absolute;
 left:50%;top:50%;
 visibility:hidden;
 }

 .content {
 position:absolute;
 width: 100%;height:100%;
 left:-50%;top:-50%;
 visibility:visible;
 }

</style>

 <div class="monitor">
  <div class="wrapper">
   <div class="content">

 ... so you hav div 200px*100px on center ...

  </div>
 </div>
</div>

You only need to calculate it for IE7 and older (and only if your content doesn't have fixed size). I suggest using HTML conditional comments to limit hack to old IEs that don't support CSS2. For all other browsers use this:

<style type="text/css">
    html,body {display:table; height:100%;width:100%;margin:0;padding:0;}
    body {display:table-cell; vertical-align:middle;}
    div {display:table; margin:0 auto; background:red;}
</style>
<body><div>test<br>test</div></body>

This is the perfect solution. It centers <div> of any size, and shrink-wraps it to size of its content.


element.offsetWidth and element.offsetHeight should do, as suggested in previous post.

However, if you just want to center the content, there is a better way of doing so. Assuming you use xhtml strict DOCTYPE. set the margin:0,auto property and required width in px to the body tag. The content gets center aligned to the page.


It is easy to modify the elements styles but kinda tricky to read the value.

JavaScript can't read any element style property (elem.style) coming from css(internal/external) unless you use the built in method call getComputedStyle in javascript.

getComputedStyle(element[, pseudo])

Element: The element to read the value for.
pseudo: A pseudo-element if required, for instance ::before. An empty string or no argument means the element itself.

The result is an object with style properties, like elem.style, but now with respect to all css classes.

For instance, here style doesn’t see the margin:

<head>
  <style> body { color: red; margin: 5px } </style>
</head>
<body>

  <script>
    let computedStyle = getComputedStyle(document.body);

    // now we can read the margin and the color from it

    alert( computedStyle.marginTop ); // 5px
    alert( computedStyle.color ); // rgb(255, 0, 0)
  </script>

</body>

So modified your javaScript code to include the getComputedStyle of the element you wish to get it's width/height or other attribute

window.onload = function() {

    var test = document.getElementById("test");
    test.addEventListener("click", select);


    function select(e) {                                  
        var elementID = e.target.id;
        var element = document.getElementById(elementID);
        let computedStyle = getComputedStyle(element);
        var width = computedStyle.width;
        console.log(element);
        console.log(width);
    }

}

Computed and resolved values

There are two concepts in CSS:

A computed style value is the value after all CSS rules and CSS inheritance is applied, as the result of the CSS cascade. It can look like height:1em or font-size:125%.

A resolved style value is the one finally applied to the element. Values like 1em or 125% are relative. The browser takes the computed value and makes all units fixed and absolute, for instance: height:20px or font-size:16px. For geometry properties resolved values may have a floating point, like width:50.5px.

A long time ago getComputedStyle was created to get computed values, but it turned out that resolved values are much more convenient, and the standard changed.
So nowadays getComputedStyle actually returns the resolved value of the property.

Please Note:

getComputedStyle requires the full property name

You should always ask for the exact property that you want, like paddingLeft or height or width. Otherwise the correct result is not guaranteed.

For instance, if there are properties paddingLeft/paddingTop, then what should we get for getComputedStyle(elem).padding? Nothing, or maybe a “generated” value from known paddings? There’s no standard rule here.

There are other inconsistencies. As an example, some browsers (Chrome) show 10px in the document below, and some of them (Firefox) – do not:

<style>
  body {
    margin: 30px;
    height: 900px;
  }
</style>
<script>
  let style = getComputedStyle(document.body);
  alert(style.margin); // empty string in Firefox
</script>

for more information https://javascript.info/styles-and-classes


According to MDN: Determining the dimensions of elements

offsetWidth and offsetHeight return the "total amount of space an element occupies, including the width of the visible content, scrollbars (if any), padding, and border"

clientWidth and clientHeight return "how much space the actual displayed content takes up, including padding but not including the border, margins, or scrollbars"

scrollWidth and scrollHeight return the "actual size of the content, regardless of how much of it is currently visible"

So it depends on whether the measured content is expected to be out of the current viewable area.


also you can use this code:

var divID = document.getElementById("divid");

var h = divID.style.pixelHeight;

It is easy to modify the elements styles but kinda tricky to read the value.

JavaScript can't read any element style property (elem.style) coming from css(internal/external) unless you use the built in method call getComputedStyle in javascript.

getComputedStyle(element[, pseudo])

Element: The element to read the value for.
pseudo: A pseudo-element if required, for instance ::before. An empty string or no argument means the element itself.

The result is an object with style properties, like elem.style, but now with respect to all css classes.

For instance, here style doesn’t see the margin:

<head>
  <style> body { color: red; margin: 5px } </style>
</head>
<body>

  <script>
    let computedStyle = getComputedStyle(document.body);

    // now we can read the margin and the color from it

    alert( computedStyle.marginTop ); // 5px
    alert( computedStyle.color ); // rgb(255, 0, 0)
  </script>

</body>

So modified your javaScript code to include the getComputedStyle of the element you wish to get it's width/height or other attribute

window.onload = function() {

    var test = document.getElementById("test");
    test.addEventListener("click", select);


    function select(e) {                                  
        var elementID = e.target.id;
        var element = document.getElementById(elementID);
        let computedStyle = getComputedStyle(element);
        var width = computedStyle.width;
        console.log(element);
        console.log(width);
    }

}

Computed and resolved values

There are two concepts in CSS:

A computed style value is the value after all CSS rules and CSS inheritance is applied, as the result of the CSS cascade. It can look like height:1em or font-size:125%.

A resolved style value is the one finally applied to the element. Values like 1em or 125% are relative. The browser takes the computed value and makes all units fixed and absolute, for instance: height:20px or font-size:16px. For geometry properties resolved values may have a floating point, like width:50.5px.

A long time ago getComputedStyle was created to get computed values, but it turned out that resolved values are much more convenient, and the standard changed.
So nowadays getComputedStyle actually returns the resolved value of the property.

Please Note:

getComputedStyle requires the full property name

You should always ask for the exact property that you want, like paddingLeft or height or width. Otherwise the correct result is not guaranteed.

For instance, if there are properties paddingLeft/paddingTop, then what should we get for getComputedStyle(elem).padding? Nothing, or maybe a “generated” value from known paddings? There’s no standard rule here.

There are other inconsistencies. As an example, some browsers (Chrome) show 10px in the document below, and some of them (Firefox) – do not:

<style>
  body {
    margin: 30px;
    height: 900px;
  }
</style>
<script>
  let style = getComputedStyle(document.body);
  alert(style.margin); // empty string in Firefox
</script>

for more information https://javascript.info/styles-and-classes


element.offsetWidth and element.offsetHeight should do, as suggested in previous post.

However, if you just want to center the content, there is a better way of doing so. Assuming you use xhtml strict DOCTYPE. set the margin:0,auto property and required width in px to the body tag. The content gets center aligned to the page.


NOTE: this answer was written in 2008. At the time the best cross-browser solution for most people really was to use jQuery. I'm leaving the answer here for posterity and, if you're using jQuery, this is a good way to do it. If you're using some other framework or pure JavaScript the accepted answer is probably the way to go.

As of jQuery 1.2.6 you can use one of the core CSS functions, height and width (or outerHeight and outerWidth, as appropriate).

var height = $("#myDiv").height();
var width = $("#myDiv").width();

var docHeight = $(document).height();
var docWidth = $(document).width();

Here is the code for WKWebView what determines a height of specific Dom element (doesn't work properly for whole page)

let html = "<body><span id=\"spanEl\" style=\"font-family: '\(taskFont.fontName)'; font-size: \(taskFont.pointSize - 4.0)pt; color: rgb(\(red), \(blue), \(green))\">\(textValue)</span></body>"
webView.navigationDelegate = self
webView.loadHTMLString(taskHTML, baseURL: nil)

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.evaluateJavaScript("document.getElementById(\"spanEl\").getBoundingClientRect().height;") { [weak self] (response, error) in
        if let nValue = response as? NSNumber {

        }
    }
}

... seems CSS help to put div on center ...

<style>
 .monitor {
 position:fixed;/* ... absolute possible if on :root */
 top:0;bottom:0;right:0;left:0;
 visibility:hidden;
 }
 .wrapper {
 width:200px;/* this is size range */
 height:100px;
 position:absolute;
 left:50%;top:50%;
 visibility:hidden;
 }

 .content {
 position:absolute;
 width: 100%;height:100%;
 left:-50%;top:-50%;
 visibility:visible;
 }

</style>

 <div class="monitor">
  <div class="wrapper">
   <div class="content">

 ... so you hav div 200px*100px on center ...

  </div>
 </div>
</div>

According to MDN: Determining the dimensions of elements

offsetWidth and offsetHeight return the "total amount of space an element occupies, including the width of the visible content, scrollbars (if any), padding, and border"

clientWidth and clientHeight return "how much space the actual displayed content takes up, including padding but not including the border, margins, or scrollbars"

scrollWidth and scrollHeight return the "actual size of the content, regardless of how much of it is currently visible"

So it depends on whether the measured content is expected to be out of the current viewable area.


Flex

In case that you want to display in your <div> some kind of popUp message on screen center - then you don't need to read size of <div> but you can use flex

_x000D_
_x000D_
.box {
  width: 50px;
  height: 20px;
  background: red;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
  position: fixed; /* remove this in case there is no content under div (and remember to set body margins to 0)*/
}
_x000D_
<div class="container">
  <div class="box">My div</div>
</div>
_x000D_
_x000D_
_x000D_


NOTE: this answer was written in 2008. At the time the best cross-browser solution for most people really was to use jQuery. I'm leaving the answer here for posterity and, if you're using jQuery, this is a good way to do it. If you're using some other framework or pure JavaScript the accepted answer is probably the way to go.

As of jQuery 1.2.6 you can use one of the core CSS functions, height and width (or outerHeight and outerWidth, as appropriate).

var height = $("#myDiv").height();
var width = $("#myDiv").width();

var docHeight = $(document).height();
var docWidth = $(document).width();

Here is the code for WKWebView what determines a height of specific Dom element (doesn't work properly for whole page)

let html = "<body><span id=\"spanEl\" style=\"font-family: '\(taskFont.fontName)'; font-size: \(taskFont.pointSize - 4.0)pt; color: rgb(\(red), \(blue), \(green))\">\(textValue)</span></body>"
webView.navigationDelegate = self
webView.loadHTMLString(taskHTML, baseURL: nil)

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.evaluateJavaScript("document.getElementById(\"spanEl\").getBoundingClientRect().height;") { [weak self] (response, error) in
        if let nValue = response as? NSNumber {

        }
    }
}

If offsetWidth returns 0, you can get element's style width property and search it for a number. "100px" -> 100

/\d*/.exec(MyElement.style.width)


Use width param as follows:

   style={{
      width: "80%",
      paddingLeft: 100,
      paddingRight: 200,
      paddingTop: 30,
      paddingBottom: 30,
      border: "3px solid lightGray",
    }}

Take a look at Element.getBoundingClientRect().

This method will return an object containing the width, height, and some other useful values:

{
    width: 960,
    height: 71,
    top: 603,
    bottom: 674,
    left: 360,
    right: 1320
}

For Example:

var element = document.getElementById('foo');
var positionInfo = element.getBoundingClientRect();
var height = positionInfo.height;
var width = positionInfo.width;

I believe this does not have the issues that .offsetWidth and .offsetHeight do where they sometimes return 0 (as discussed in the comments here)

Another difference is getBoundingClientRect() may return fractional pixels, where .offsetWidth and .offsetHeight will round to the nearest integer.

IE8 Note: getBoundingClientRect does not return height and width on IE8 and below.*

If you must support IE8, use .offsetWidth and .offsetHeight:

var height = element.offsetHeight;
var width = element.offsetWidth;

Its worth noting that the Object returned by this method is not really a normal object. Its properties are not enumerable (so, for example, Object.keys doesn't work out-of-the-box.)

More info on this here: How best to convert a ClientRect / DomRect into a plain Object

Reference:


Flex

In case that you want to display in your <div> some kind of popUp message on screen center - then you don't need to read size of <div> but you can use flex

_x000D_
_x000D_
.box {
  width: 50px;
  height: 20px;
  background: red;
}

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
  position: fixed; /* remove this in case there is no content under div (and remember to set body margins to 0)*/
}
_x000D_
<div class="container">
  <div class="box">My div</div>
</div>
_x000D_
_x000D_
_x000D_


NOTE: this answer was written in 2008. At the time the best cross-browser solution for most people really was to use jQuery. I'm leaving the answer here for posterity and, if you're using jQuery, this is a good way to do it. If you're using some other framework or pure JavaScript the accepted answer is probably the way to go.

As of jQuery 1.2.6 you can use one of the core CSS functions, height and width (or outerHeight and outerWidth, as appropriate).

var height = $("#myDiv").height();
var width = $("#myDiv").width();

var docHeight = $(document).height();
var docWidth = $(document).width();

element.offsetWidth and element.offsetHeight should do, as suggested in previous post.

However, if you just want to center the content, there is a better way of doing so. Assuming you use xhtml strict DOCTYPE. set the margin:0,auto property and required width in px to the body tag. The content gets center aligned to the page.


also you can use this code:

var divID = document.getElementById("divid");

var h = divID.style.pixelHeight;

NOTE: this answer was written in 2008. At the time the best cross-browser solution for most people really was to use jQuery. I'm leaving the answer here for posterity and, if you're using jQuery, this is a good way to do it. If you're using some other framework or pure JavaScript the accepted answer is probably the way to go.

As of jQuery 1.2.6 you can use one of the core CSS functions, height and width (or outerHeight and outerWidth, as appropriate).

var height = $("#myDiv").height();
var width = $("#myDiv").width();

var docHeight = $(document).height();
var docWidth = $(document).width();

Use width param as follows:

   style={{
      width: "80%",
      paddingLeft: 100,
      paddingRight: 200,
      paddingTop: 30,
      paddingBottom: 30,
      border: "3px solid lightGray",
    }}

Just in case it is useful to anyone, I put a textbox, button and div all with the same css:

width:200px;
height:20px;
border:solid 1px #000;
padding:2px;

<input id="t" type="text" />
<input id="b" type="button" />
<div   id="d"></div>

I tried it in chrome, firefox and ie-edge, I tried with jquery and without, and I tried it with and without box-sizing:border-box. Always with <!DOCTYPE html>

The results:

                                                               Firefox       Chrome        IE-Edge    
                                                              with   w/o    with   w/o    with   w/o     box-sizing

$("#t").width()                                               194    200    194    200    194    200
$("#b").width()                                               194    194    194    194    194    194
$("#d").width()                                               194    200    194    200    194    200

$("#t").outerWidth()                                          200    206    200    206    200    206
$("#b").outerWidth()                                          200    200    200    200    200    200
$("#d").outerWidth()                                          200    206    200    206    200    206

$("#t").innerWidth()                                          198    204    198    204    198    204
$("#b").innerWidth()                                          198    198    198    198    198    198
$("#d").innerWidth()                                          198    204    198    204    198    204

$("#t").css('width')                                          200px  200px  200px  200px  200px  200px
$("#b").css('width')                                          200px  200px  200px  200px  200px  200px
$("#d").css('width')                                          200px  200px  200px  200px  200px  200px

$("#t").css('border-left-width')                              1px    1px    1px    1px    1px    1px
$("#b").css('border-left-width')                              1px    1px    1px    1px    1px    1px
$("#d").css('border-left-width')                              1px    1px    1px    1px    1px    1px

$("#t").css('padding-left')                                   2px    2px    2px    2px    2px    2px
$("#b").css('padding-left')                                   2px    2px    2px    2px    2px    2px
$("#d").css('padding-left')                                   2px    2px    2px    2px    2px    2px

document.getElementById("t").getBoundingClientRect().width    200    206    200    206    200    206
document.getElementById("b").getBoundingClientRect().width    200    200    200    200    200    200
document.getElementById("d").getBoundingClientRect().width    200    206    200    206    200    206

document.getElementById("t").offsetWidth                      200    206    200    206    200    206
document.getElementById("b").offsetWidth                      200    200    200    200    200    200
document.getElementById("d").offsetWidth                      200    206    200    206    200    206

You only need to calculate it for IE7 and older (and only if your content doesn't have fixed size). I suggest using HTML conditional comments to limit hack to old IEs that don't support CSS2. For all other browsers use this:

<style type="text/css">
    html,body {display:table; height:100%;width:100%;margin:0;padding:0;}
    body {display:table-cell; vertical-align:middle;}
    div {display:table; margin:0 auto; background:red;}
</style>
<body><div>test<br>test</div></body>

This is the perfect solution. It centers <div> of any size, and shrink-wraps it to size of its content.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to dhtml

Child element click event trigger the parent click event Change :hover CSS properties with JavaScript Modifying a query string without reloading the page Adding and removing style attribute from div with jquery Set content of HTML <span> with Javascript jQuery get the id/value of <li> element after click function Capture iframe load complete event How do I attach events to dynamic HTML elements with jQuery? How do I programmatically click on an element in JavaScript? Getting all selected checkboxes in an array