jQuery: height()/width() and "display:none"
I always thought elements that had display:none
CSS style returned 0 for height()
and width()
.
But in this example:
HTML
<div id="target" style="display:none;">
a
</div>
CSS
alert($("#target").height());
they don't: http://jsfiddle.net/Gts6A/2/
How come? I've seen 0 come back plenty of times in the past.
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()
.
EDIT
This appears to have been corrected as of jQuery 1.4.4
Example: http://jsfiddle.net/GALc7/1/
I believe this is only true for items whose parent is "display:none"
See this article on the matter http://dev.jquery.com/ticket/125
Also, see this example (save as an .html file) or see ( http://jsfiddle.net/GALc7/ )
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
alert($("#target").height());
});
</script>
</head>
<body>
<div id="parent" style="display:none;">
<div id="target" style="height:100px;display:block;">
a
</div>
</div>
</body>
</html>