1209

How can I calculate the width and height of a <div> element, so as to be able to center it in the browser's display (viewport)? What browsers support each technique?

1
  • 19
    Keep in mind that getting an element's height through any method always has a performance impact as it makes the browser recalculate the position of all elements in the page (reflow). Therefore, avoid doing it too much. Checkout this list for what kind of things trigger a reflow. Commented Dec 5, 2016 at 3:16

17 Answers 17

1703

You should use the .offsetWidth and .offsetHeight properties. Note they belong to the element, not .style.

var width = document.getElementById('foo').offsetWidth;

The .getBoundingClientRect() function returns the dimensions and location of the element as floating-point numbers after performing CSS transforms.

> console.log(document.getElementById('foo').getBoundingClientRect())
DOMRect {
    bottom: 177,
    height: 54.7,
    left: 278.5,​
    right: 909.5,
    top: 122.3,
    width: 631,
    x: 278.5,
    y: 122.3,
}
13
  • 214
    Beware! offsetHeight/offsetWidth can return 0 if you've done certain DOM modifications to the element recently. You may have to call this code in a setTimeout call after you've modified the element. Commented Jan 19, 2010 at 5:59
  • 36
    Under what circumstances does it return 0?
    – Cheetah
    Commented Feb 22, 2012 at 23:22
  • 7
    I can't pinpoint the reason that offsetWidth is returning 0 in my case, because I didn't originally write the code, but within the onload event I get always 0.
    – JDandChips
    Commented Nov 2, 2012 at 8:52
  • 59
    @JDandChips: offsetWidth will be 0 if the element is display:none, whereas the computed width might still have a positive value in this instance. visibility:hidden does not affect the offsetWidth.
    – MrWhite
    Commented Nov 16, 2012 at 0:16
  • 30
    @Supuhstar both have different meanings. offsetWidth returns the "whole" box including content, padding, and borders; while clientWidth returns the size of the content box alone (so it will have a smaller value whenever the element has any non-zero padding and/or border). (mod edited for clarity) Commented Dec 1, 2014 at 14:41
272

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:

2
  • 18
    getboundingClientRect() will return the actual width and height of elements scaled via css whereas offsetHeight and offsetWidth will not.
    – Luke
    Commented Mar 5, 2016 at 1:16
  • 1
    @Luke not just that it will return floating point number which is a necesessity if you ever need to work with precise calculations, like cropper implementations.
    – ado387
    Commented Aug 22, 2023 at 11:41
78

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();
0
63

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
4
  • 2
    Just to be clear... do any of those browsers do anything differently from eachother? I cannot find any differences... Also, I'm not down-voting (yet), but this doesn't really directly answer the question, though it could be easily editted to do so. Commented Mar 11, 2016 at 19:35
  • 4
    Wasn't aimed at answering the question - its already been answered. Just some helpful information and yes all the main latest version browsers do agree on these values - which is a good thing.
    – Graham
    Commented Mar 14, 2016 at 11:13
  • 5
    Well... if your intent is not to answer the question, then this doesn't really belong here (as an "answer"). I would consider putting this in some external resource (maybe a GitHub gist, or a blog post) and linking it in a comment on the original Question or one of the answers. Commented Mar 14, 2016 at 19:50
  • 25
    @ZachLysobey There's exceptions to every rule - and this is a cool, useful thing to see. Commented Sep 12, 2016 at 9:28
39

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.

1
8

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

6

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.

4

This is the only thing that worked for me:

element.clientWidth -
parseFloat(window.getComputedStyle(element, null).getPropertyValue("padding-left")) -
parseFloat(window.getComputedStyle(element, null).getPropertyValue("padding-right"))
2

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.

1
  • 1
    I think he wants to center it vertically too, which is a right pain with CSS unless you can meet some specific criteria (e.g. known-size content)
    – Greg
    Commented Nov 16, 2008 at 19:53
2

also you can use this code:

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

var h = divID.style.pixelHeight;
2
  • 2
    Hmm, works in Chrome and IE9, doesn't appear to work in Firefox. Does it only work for certain doc types? Commented Aug 19, 2011 at 20:00
  • 3
    pixelHeight was an Internet Explorer invention which should not be used anymore stackoverflow.com/q/17405066/2194590 Commented Apr 15, 2019 at 13:15
2
div.clientHeight;
div.clientWidth;
2
  • 5
    This answer is in a desperate need of some explanations...
    – Tomerikoo
    Commented Apr 30, 2023 at 12:43
  • While possibly correct, a code-only answer helps the person who asked the question, it doesn't do them or future visitors any good. Please consider improving your answer. Commented May 1, 2023 at 4:10
1

... 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>
1

I created a utility function for this, with high flexibility:

export type Size = {width: number, height: number};
export enum GetSize_Method {
    /** Includes: content, padding. Excludes: border, margin, scroll-bar (if it has one), "position:absolute" descendants. */
    ClientSize = "ClientSize",
    /** Includes: content, padding, border, margin, scroll-bar (if it has one). Excludes: "position:absolute" descendants. */
    OffsetSize = "OffsetSize",
    /** Includes: content, padding, border, margin, scroll-bar (if it has one), "position:absolute" descendants. Excludes: none. */
    ScrollSize = "ScrollSize",
    /** Same as ScrollSize, except that it's calculated after the element's css transforms are applied. */
    BoundingClientRect = "BoundingClientRect",
    /** Lets you specify the exact list of components you want to include in the size calculation. */
    Custom = "Custom",
}
export type SizeComp = "content" | "padding" | "border" | "margin" | "scrollBar" | "posAbsDescendants";

export function GetSize(el: HTMLElement, method = GetSize_Method.ClientSize, custom_sizeComps?: SizeComp[]) {
    let size: Size;
    if (method == GetSize_Method.ClientSize) {
        size = {width: el.clientWidth, height: el.clientHeight};
    } else if (method == GetSize_Method.OffsetSize) {
        size = {width: el.offsetWidth, height: el.offsetHeight};
    } else if (method == GetSize_Method.ScrollSize) {
        size = {width: el.scrollWidth, height: el.scrollHeight};
    } else if (method == GetSize_Method.BoundingClientRect) {
        const rect = el.getBoundingClientRect();
        size = {width: rect.width, height: rect.height};
    } else if (method == GetSize_Method.Custom) {
        const style = window.getComputedStyle(el, null);
        const styleProp = (name: string)=>parseFloat(style.getPropertyValue(name));

        const padding = {w: styleProp("padding-left") + styleProp("padding-right"), h: styleProp("padding-top") + styleProp("padding-bottom")};
        const base = {w: el.clientWidth - padding.w, h: el.clientHeight - padding.h};
        const border = {w: styleProp("border-left") + styleProp("border-right"), h: styleProp("border-top") + styleProp("border-bottom")};
        const margin = {w: styleProp("margin-left") + styleProp("margin-right"), h: styleProp("margin-top") + styleProp("margin-bottom")};
        const scrollBar = {w: (el.offsetWidth - el.clientWidth) - border.w - margin.w, h: (el.offsetHeight - el.clientHeight) - border.h - margin.h};
        const posAbsDescendants = {w: el.scrollWidth - el.offsetWidth, h: el.scrollHeight - el.offsetHeight};

        const sc = (name: SizeComp, valIfEnabled: number)=>custom_sizeComps.includes(name) ? valIfEnabled : 0;
        size = {
            width: sc("content", base.w) + sc("padding", padding.w) + sc("border", border.w)
                    + sc("margin", margin.w) + sc("scrollBar", scrollBar.w) + sc("posAbsDescendants", posAbsDescendants.w),
            height: sc("content", base.h) + sc("padding", padding.h) + sc("border", border.h)
                    + sc("margin", margin.h) + sc("scrollBar", scrollBar.h) + sc("posAbsDescendants", posAbsDescendants.h),
        };
    }
    return size;
}

Usage:

const el = document.querySelector(".my-element");
console.log("Size:", GetSize(el, "ClientSize"));
console.log("Size:", GetSize(el, "Custom", ["content", "padding", "border"]));
0

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

.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)*/
}
<div class="container">
  <div class="box">My div</div>
</div>

-4

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)

-4

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 {

        }
    }
}
1
  • 1
    just to be clear, this is iOS swift code, right? Not JavaScript. I'm witholding a downvote (b/c this may actually be pretty useful) but please note that this does not answer the question, and would likely be more appropriate on another, iOS specific, question. If none already exists, perhaps consider asking one and self-answering. Commented Oct 30, 2018 at 21:19
-6

Use width param as follows:

   style={{
      width: "80%",
      paddingLeft: 100,
      paddingRight: 200,
      paddingTop: 30,
      paddingBottom: 30,
      border: "3px solid lightGray",
    }}
1
  • that looks like its a JSX attribute for setting width? Commented May 7, 2021 at 21:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.