jQuery Dimensions
To get and set the CSS dimensions for the objects, jQuery provides several methods such as height()
, innerHeight()
, outerHeight()
, width()
, innerWidth()
, and outerWidth()
. To understand how these methods calculate the dimensions of an element's box, look at the diagram below.
The width() and height() method
The width()
and height()
methods in jQuery get and set the element's width and height, respectively. The padding, border, and margin on the element are not included in the width and height. The width and height of a <div>
element are returned in the following example.
$(document).ready(function(){
$("button").click(function(){
var divWidth = $("#box").width();
var divHeight = $("#box").height();
$("#result").html("Width: " + divWidth + ", " + "Height: " + divHeight);
});
});
Live Demo!
Similarly, you may change the element's width and height by passing the value as a parameter to the width()
and height()
methods. A string (number and unit, e.g. 100px, 20em, etc.) or a number may be used as the value. The width and height of a <div>
element are set to 400
pixels and 300
pixels, respectively, in the following example.
$(document).ready(function(){
$("button").click(function(){
$("#box").width(400).height(300);
});
});
Live Demo!
The innerWidth() and innerHeight() method
The innerWidth()
and innerHeight()
methods in jQuery get and set the element's inner width and height, respectively. The padding is included in the inner width and height, but the element's border and margin are not. On clicking a button, the following example returns the inner width and height of a <div>
element.
$(document).ready(function(){
$("button").click(function(){
var divWidth = $("#box").innerWidth();
var divHeight = $("#box").innerHeight();
$("#result").html("Inner Width: " + divWidth + ", " + "Inner Height: " + divHeight);
});
});
Live Demo!
The outerWidth() and outerHeight() method
The jQuery methods outerWidth()
and outerHeight()
get and set the element's outer width and height, respectively. The padding and border are included in the outer width and height, but the element's margin is not. On clicking a button, the following example returns the outer width and height of a <div>
element.
$(document).ready(function(){
$("button").click(function(){
var divWidth = $("#box").outerWidth();
var divHeight = $("#box").outerHeight();
$("#result").html("Outer Width: " + divWidth + ", " + "Outer Height: " + divHeight);
});
});
Live Demo!