Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 56 ยท Manipulating the DOM

Dimensions, Position and Scrolling

Measure and place elements with jQuery: width, height, innerWidth, outerWidth(true), offset, position, scrollTop and scrollLeft, with box-sizing explained.

Sooner or later a script needs numbers: how wide is this panel, where on the page is that button, how far has the visitor scrolled? Plain CSS values are not much help, because width: 50% or auto is not a size you can calculate with. jQuery gives you a set of methods that return real numbers in pixels and that behave the same way whether the element has padding, borders or a different box-sizing.

The key to all of them is the box model. Every element is a stack of four layers, and each jQuery method answers the question "up to which layer?"

The four layers

Content The text or image area itself.
Padding Space inside the border.
Border The frame line.
Margin Space outside, between neighbors.
1 / 2

Width and height

For an element with width: 200px; padding: 10px; border: 5px solid; margin: 20px and the default box-sizing: content-box:

Call Result What it includes
.width() 200 content
.innerWidth() 220 content + padding
.outerWidth() 230 content + padding + border
.outerWidth(true) 270 content + padding + border + margin

The height methods work the same way. All of them return numbers without units, so you can do arithmetic directly: $("#a").width() + $("#b").width(). Since jQuery 3 the numbers can be fractional (for example 199.5) when the layout is fractional, so round them with Math.round() if you need whole pixels.

These methods are one-argument getters for the first element. To set a size, pass a number or a string with units; jQuery treats a bare number as pixels:

JavaScript
$("#panel").width(300);            // 300px
$("#panel").height("50%");         // a string with a unit is used as written
$("#panel").width("+=50");         // relative: 50 pixels wider

box-sizing does not change the answer

If the stylesheet says box-sizing: border-box, the CSS width of 200px already includes padding and border. A lot of code gets confused here, but jQuery does not: .width() still returns the content width. With width: 200px; padding: 10px; border: 5px; box-sizing: border-box, .width() is 170, .innerWidth() is 190 and .outerWidth() is 200. When you set .width(100) on such an element, jQuery adjusts the CSS so the content ends up 100 pixels wide. That consistency is the main reason to prefer these methods over reading .css("width"), which returns whatever the stylesheet says for that box model.

The four widths of one box

Window and document sizes

Pass the browser window or the page to jQuery and the same methods measure those:

JavaScript
$(window).width();      // width of the viewport (the visible area)
$(window).height();     // height of the viewport
$(document).width();    // width of the whole page
$(document).height();   // height of the whole page, including what you must scroll to

The viewport changes as the user resizes the window; the document size changes as content is added. Reading either one is cheap, but doing it on every scroll or resize event can make a page sluggish, a topic covered with throttling in Mouse, Keyboard and Form Events.

Position on the page: offset and position

Two methods tell you where an element is. They differ in what they measure from.

  • .offset() returns { top, left } relative to the document. It is the right choice when you need absolute page coordinates, for example to draw a tooltip next to an element.
  • .position() returns { top, left } relative to the element's offset parent, which is the closest ancestor that is positioned (relative, absolute or fixed). Use it when you move the element with CSS top and left inside its container.

Both are getters for the first element. .offset({ top: 100, left: 40 }) can also set the position, adjusting the element's CSS so it ends up at those document coordinates. .position() is read-only.

Be careful with one trap: .offset() measures relative to the document, so it does not change when the page scrolls. A visitor scrolling down by 300px does not make .offset().top smaller, while the element's position on screen does move. To find where an element is within the visible viewport, subtract the scroll: $("#x").offset().top - $(window).scrollTop().

offset() versus position()

Scrolling

.scrollTop() and .scrollLeft() read or set how far an element, or the page, has been scrolled. With no argument they return the current number of pixels; with a number they scroll.

JavaScript
$(window).scrollTop();             // how far the page is scrolled down
$(window).scrollTop(0);            // jump to the top
$("#chat").scrollTop(1000);        // scroll a scrollable element
$("#chat").scrollTop($("#chat")[0].scrollHeight);  // to the bottom

Setting scrollTop jumps instantly. To scroll smoothly, animate it, which is the subject of Custom Animations with .animate().

A common pattern combines the pieces above: show a "back to top" button once $(window).scrollTop() passes a threshold, and use $(document).height() - $(window).height() as the maximum scroll value when you need to compute a percentage.

A scroll-aware box

Practical advice

  • Measure after the content is in place. Images that have not loaded yet have no size, so wait for the load event if you depend on them.
  • Hidden elements (display: none) are measured by jQuery by briefly showing them off-screen, but this is slower and can be wrong for complicated cases. Measure visible elements when you can.
  • Do not measure repeatedly inside loops or scroll handlers; store the number in a variable.
  • For the raw browser rectangle, el.getBoundingClientRect() is the native counterpart, and it is relative to the viewport.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. An element has width 200px, padding 10px, a 5px border and a 20px margin (content-box). What does .outerWidth(true) return?

    200 content + 20 padding (both sides) + 10 border + 40 margin = 270. outerWidth() without true stops at the border and gives 230.
  2. 2. With box-sizing: border-box, width: 200px, padding 10px and a 5px border, what is .width()?

    jQuery always reports the content width, which is 200 minus 20 padding minus 10 border, so 170.
  3. 3. Which method returns coordinates relative to the whole document?

    .offset() is measured from the top left of the document, while .position() is measured from the offset parent.
  4. 4. What does $(document).height() minus $(window).height() give you?

    The document height is the full page and the window height is the visible part, so the difference is how far the page can scroll.

Summary

  • .width() and .height() measure the content; .innerWidth() adds padding; .outerWidth() adds the border; .outerWidth(true) adds the margin.
  • They return plain numbers in pixels, can be fractional in jQuery 3, and ignore box-sizing differences for you.
  • $(window) measures the viewport and $(document) measures the whole page.
  • .offset() gives document coordinates; .position() gives coordinates inside the offset parent.
  • .scrollTop() and .scrollLeft() read or set scroll positions on the page or any scrollable element.
  • Measure after layout exists, cache results, and avoid reading sizes in tight loops.

Next, start responding to users with Handling Events.