jQuery: .height()/.width() and "display:none"
Despite the popular assumption that elements with "display:none" return zero for jQuery's .height() and .width() methods, this is not always the case. In the provided example, the target element returns a non-zero height even though it is hidden.
Why does this occur?
According to jQuery's source code, if an element's offsetWidth is 0 (indicating that jQuery considers it "hidden"), a series of steps are taken to determine the height:
This effectively moves the element out of the document flow, calculates the height while accounting for border/padding, and then reverts the previous settings.
So, jQuery essentially makes the element visible temporarily, calculates the height, and makes it invisible again, all before the UI actually updates. This allows .height() and .width() to work even on hidden elements as long as their parents are visible.
The .height() and .width() methods handle this showing/hiding process internally, so developers do not need to manually implement such checks in their code.
The above is the detailed content of Why does jQuery\'s `.height()` and `.width()` methods return values for elements with `display: none`?. For more information, please follow other related articles on the PHP Chinese website!