SyntaxStudy
Sign Up
jQuery Intermediate 5 min read

jQuery Dimensions

Accurately measuring element size is essential for layout calculations, drag-and-drop, and responsive components. jQuery provides a clean set of dimension methods that abstract the confusing native properties like offsetWidth, clientWidth, and scrollWidth.

Width and Height Methods

.width() and .height() return the content area dimensions excluding padding, border, and margin. .innerWidth() / .innerHeight() include padding, and .outerWidth() / .outerHeight() also include the border. Pass true to the outer methods to include the margin as well.

Setting Dimensions

All these methods double as setters when you pass a value. You can pass a number (treated as pixels) or a string with a unit like '50%'.

  • .width() — content width only
  • .innerWidth() — content + padding
  • .outerWidth() — content + padding + border
  • .outerWidth(true) — all of the above + margin

To get the full document or viewport dimensions use $(document).height() or $(window).width() respectively.

Example
// Read dimensions
var w = $('#sidebar').width();
var h = $('#sidebar').outerHeight(true); // includes margin

console.log('Width: ' + w + ', Height: ' + h);

// Set dimensions
$('#hero').width($(window).width());
$('#hero').height(400);

// Viewport dimensions
var vpW = $(window).width();
var vpH = $(window).height();
console.log('Viewport: ' + vpW + 'x' + vpH);

// Document total height
console.log('Page height: ' + $(document).height());
Pro Tip

Use .outerHeight(true) when you need the total space an element occupies including its margin.