jQuery Dimensions

jQuery gives you simple methods to measure how big elements are and where they sit. This is useful for layout math, positioning tooltips, or resizing things to fit their container.

Measuring elements with jQuery

Every visible element on a page takes up space made of its content, padding, border, and margin. jQuery has a method for each layer so you can measure exactly the part you care about.

  • width() and height() - the content area only, without padding, border, or margin.
  • innerWidth() and innerHeight() - content plus padding.
  • outerWidth() and outerHeight() - content plus padding plus border.
  • outerWidth(true) and outerHeight(true) - content, padding, border, and margin.

Read width and height

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>

<div id="box" style="width:200px; height:100px;">Box content</div>

<script>
var w = $("#box").width();
var h = $("#box").height();
console.log("Box is " + w + " by " + h);
</script>

</body>
</html>

Setting dimensions

The same width() and height() methods can also set a size. Pass a number, which jQuery treats as pixels, or a string with units.

Set the size of an element

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>

<div id="box">Box content</div>

<script>
$("#box").width(300);
$("#box").height("150px");
</script>

</body>
</html>

Compare inner and outer measurements

<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>

<div id="box" style="width:200px; padding:20px; border:5px solid black; margin:10px;">Box content</div>

<script>
$("#box").innerWidth();      // content + padding
$("#box").outerWidth();      // content + padding + border
$("#box").outerWidth(true);  // also includes margin
</script>

</body>
</html>
MethodIncludes contentIncludes paddingIncludes borderIncludes margin
width() / height()YesNoNoNo
innerWidth() / innerHeight()YesYesNoNo
outerWidth() / outerHeight()YesYesYesNo
outerWidth(true) / outerHeight(true)YesYesYesYes
Note: width() always returns a number, while css('width') returns a string like '300px'. Use width() when you want to do math with the value.

Exercise: jQuery Dimensions

What does .width() return for an element?