jQuery provides several built-in methods to get and set the dimensions of HTML elements in a simple and consistent way.
This box has 20px Padding and a 10px Border.
Notice how methods include or exclude padding/borders.
width() and height() work with content size onlywidth() – Get/set width (no padding, border, margin)height() – Get/set heightinnerWidth() – Width + paddinginnerHeight() – Height + paddingouterWidth() – Padding + border (+ margin optional)outerHeight() – Padding + border (+ margin optional)
// 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);
// 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);
});
outerHeight(true) when margins matter