views:

65

answers:

2

I always thought elements that had "display:none" CSS style returned 0 for height() and width().

But in this example, they don't: http://jsfiddle.net/Gts6A/2/

How come? I've seen 0 come back plenty of times in the past.

+1  A: 

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)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;
<html>
<head>
    <title>Example</title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;

    <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>
Brandon Boone
+4  A: 

If an element has an offsetWidth of 0 (juery 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 jQuery.curCSS(elem, "height"), 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().

Nick Craver