To build truly responsive and dynamic layouts, you often need to know the exact size of an element. jQuery provides a suite of methods that allow you to calculate width and height according to the CSS Box Model, including or excluding padding, borders, and margins.
Before using measurement methods, it is important to visualize what each one includes:
| Method | What it measures... |
|---|---|
width() / height() |
Content only (excludes padding, border, and margin). |
innerWidth() / innerHeight() |
Content + Padding. |
outerWidth() / outerHeight() |
Content + Padding + Border. |
outerWidth(true) / outerHeight(true) |
Content + Padding + Border + **Margin**. |
The width() and height() methods can be used to either get the
current size or set a new size for an element.
// GETting the width
var w = $("#box").width();
// SETting the width
$("#box").width(500); // 500px
These methods are vital when you are trying to align elements perfectly or calculate the total space an element occupies on the screen.
// Includes content + padding
var inner = $("#box").innerWidth();
// Includes content + padding + border
var outer = $("#box").outerWidth();
// Total space (includes everything + margin)
var total = $("#box").outerWidth(true);
You aren't limited to just HTML elements. You can also measure the current browser viewport (window) or the entire HTML document.
// Width of the browser viewport
$(window).width();
// Height of the entire HTML document
$(document).height();
$(window).width() minus half of the element's
outerWidth().
Here is how you might display an element's dimensions on the screen for debugging or UI purposes.
$("button").click(function() {
var txt = "";
txt += "Width: " + $("#div1").width() + "px<br>";
txt += "Inner Width: " + $("#div1").innerWidth() + "px<br>";
txt += "Outer Width: " + $("#div1").outerWidth() + "px<br>";
txt += "Outer Width (w/ margin): " + $("#div1").outerWidth(true) + "px";
$("#info").html(txt);
});
.css("width") method, which returns a
string with "px" (e.g., "500px"), the .width() method returns a **pure
number** (e.g., 500). This makes it much easier to use in calculations.