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.
jQuery has several important methods for working with dimensions:
width() and height()innerWidth() and innerHeight()outerWidth() and outerHeight()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).
$("button").click(function(){
var txt = "";
txt += "Width: " + $("#div1").width() + "";
txt += "Height: " + $("#div1").height();
$("#div1").html(txt);
});
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.
$("button").click(function(){
var txt = "";
txt += "Inner width: " + $("#div1").innerWidth() + "";
txt += "Inner height: " + $("#div1").innerHeight();
$("#div1").html(txt);
});
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).
$("button").click(function(){
var txt = "";
txt += "Outer width: " + $("#div1").outerWidth() + "";
txt += "Outer height: " + $("#div1").outerHeight();
$("#div1").html(txt);
});
You can also use width() and height() to actively resize elements.
Simply pass the new value as a parameter inside the method.
$("button").click(function(){
$("#div1").width(500).height(500);
});
Which jQuery method returns the width of an element, including both its padding AND its border?
How do you use outerWidth() to include the CSS margin in its calculation?