jQuery: height()/width() and “display:none”

If an element has an offsetWidth of 0 (jQuery is considering this “hidden”), checked here, then it attempts to figure out what the height should be. It sets the following properties on the element via jQuery.swap() for the duration of the check:

  • position: "absolute"
  • visibility: "hidden"
  • display: "block"

Then it gets the height, via getWidthOrHeight(...) which adds border/padding if necessary via augmentWidthOrHeight(...) depending on the box model, and reverts all of the above properties to their former values.

So basically it’s taking the element, showing it out of the flow of the document, getting the height, then hiding it again, all before the UI thread updates so you never see this happen. It’s doing this so .height()/.width() works, even on elements that are currently hidden, as long as their parents are visible…so you can run .height()/.width(), without doing the show/hide trick it’s doing in your code, it’s handled within .height() and .width().

Leave a Comment