David Jones

Getting the width and height including padding, margin and border

The other day I was trying to get he height and width of a div using jQuery, so as you might expect I used the width and height methods. So my code looked something like this.

var my_div = $( '#js-my-div' ),
       my_width = my_div.width(),
       my_height = my_div.height();

If the div in question has a margin, some padding or a border applied to it and you wanted to get the overall dimensions of the div then this would not give you the correct width and height. I my case I was expecting the div to have a height and width of 200px but because the div had a border of 5px the height and width values returned were 190px.

Luckily jQuery has another couple of methods that get the outer height and the outer width of an element. Not surprisingly they are called outerwidth and outerheight and they are used in exactly the same way.

var my_div = $( '#js-my-div' ),
       my_width = my_div.outerWidth(),
       my_height = my_div.outerHeight();