jQuery Dimensions

jQuery Dimensions

When working with web layouts, you frequently need to calculate the physical size of elements on the screen.

jQuery provides several methods to easily calculate width and height, accounting for padding and borders.


The jQuery Dimension Methods

jQuery has several important methods for working with dimensions:


The width() and height() Methods

The width() method sets or returns the width of an element (excludes padding, borders, and margins).

The height() method sets or returns the height of an element (excludes padding, borders, and margins).

Width and Height Example:

$("button").click(function(){
  var txt = "";
  txt += "Width: " + $("#div1").width() + "
"; txt += "Height: " + $("#div1").height(); $("#div1").html(txt); });

The innerWidth() and innerHeight() Methods

The innerWidth() method returns the width of an element, including padding.

The innerHeight() method returns the height of an element, including padding.

This is very useful when calculating the physical area content has to flow within.

Inner Dimensions Example:

$("button").click(function(){
  var txt = "";
  txt += "Inner width: " + $("#div1").innerWidth() + "
"; txt += "Inner height: " + $("#div1").innerHeight(); $("#div1").html(txt); });

The outerWidth() and outerHeight() Methods

The outerWidth() method returns the width of an element, including padding and borders.

The outerHeight() method returns the height of an element, including padding and borders.

If you need to include the margin as well, you can pass true as a parameter: outerWidth(true).

Outer Dimensions Example:

$("button").click(function(){
  var txt = "";
  txt += "Outer width: " + $("#div1").outerWidth() + "
"; txt += "Outer height: " + $("#div1").outerHeight(); $("#div1").html(txt); });

Setting Dimensions

You can also use width() and height() to actively resize elements.

Simply pass the new value as a parameter inside the method.

Resize Element Example:

$("button").click(function(){
  $("#div1").width(500).height(500);
});

Exercise 1 of 2

?

Which jQuery method returns the width of an element, including both its padding AND its border?

Exercise 2 of 2

?

How do you use outerWidth() to include the CSS margin in its calculation?