HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

jQuery Dimensions

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.


Understanding the Box Model

Before using measurement methods, it is important to visualize what each one includes:

Border
Padding
CONTENT

Dimension Methods Reference

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

1. Basic Width and Height

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

2. Inner and Outer Dimensions

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);

Measuring the Browser Window

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();
Practical Use: Centering a custom modal or popup often requires calculating half of the $(window).width() minus half of the element's outerWidth().

Practical Example: Info Reveal

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);
});
Pro Tip: Unlike the .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.

Key Points to Remember

  • width() is the core content size.
  • outerWidth(true) is the "real world" footprint of the element.
  • All these methods return **numbers**, not strings.
  • You can measure $(window) and $(document) as well.
  • Values can be set by passing a number as an argument.