← Back to Chapters

jQuery Dimensions

? jQuery Dimensions

? Quick Overview

jQuery provides several built-in methods to get and set the dimensions of HTML elements in a simple and consistent way.

? Live Dimension Explorer

This box has 20px Padding and a 10px Border.

 
width() 0
innerWidth() 0
outerWidth() 0
outerWidth(true) 0

Notice how methods include or exclude padding/borders.

? Key Concepts

  • width() and height() work with content size only
  • Inner methods include padding
  • Outer methods include borders and optionally margins

? Common Methods

  • width() – Get/set width (no padding, border, margin)
  • height() – Get/set height
  • innerWidth() – Width + padding
  • innerHeight() – Height + padding
  • outerWidth() – Padding + border (+ margin optional)
  • outerHeight() – Padding + border (+ margin optional)

? Interactive Example

Demo Box
? View Code Example
// Reading element dimensions using jQuery
let w = $('#element').width();
let h = $('#element').height();
let iw = $('#element').innerWidth();
let oh = $('#element').outerHeight(true);

// Setting element dimensions using numbers (pixels)
$('#element').width(300);
$('#element').height(150);

? Animate Dimensions Smoothly

Animate Me
? View Code Example
// Smoothly animate width and height using jQuery animate()
$('#smallBtn').click(function() {
$('#animateBox').animate({ width: 100, height: 50 }, 600);
});
$('#largeBtn').click(function() {
$('#animateBox').animate({ width: 300, height: 150 }, 600);
});
$('#resetBtn').click(function() {
$('#animateBox').animate({ width: 200, height: 100 }, 600);
});

? Use Cases

  • Building responsive UI components
  • Animating layouts dynamically
  • Calculating space for dashboards and widgets

✅ Tips & Best Practices

  • Use outerHeight(true) when margins matter
  • Always pass numbers, not strings
  • Use animations for smoother UX

? Try It Yourself

  • Change box size on window resize
  • Create a toggle size button
  • Combine with CSS transitions