I’m trying to get the height of a div container that has no height initially set and contains a floated element. The offsetHeight property keeps coming up 0. I am able to get the height if I set the containing div’s overflow property to hidden. Is there a better method than this?
I have an example in jsFiddle – http://jsfiddle.net/6RQMb/. It’s my first time using jsFiddle for testing, so let me know if I did anything incorrectly…
In case I messed something up with jsFiddle (and because stackoverflow requested it), here’s the example info:
HTML
<div id="container"><p>Some text that gives this element height</p></div>
CSS
p {float:left;}
/* uncomment next line and it works, without it the alert comes back with 0
#container {overflow:hidden;}
*/
JAVASCRIPT
alert( document.getElementById('container').offsetHeight );
You can use the
clearfixmethod to force your container element to “expand” and actually wrap all its child floating elements.This technique requires that the browser support CSS generated content. There are variants of this technique that can be used to support browsers as low as IE6. Chris Coyier explains here.
Here it is in action: http://jsfiddle.net/remibreton/2vQVJ/1/
EDIT: If you’re only interested in supporting IE8+, you can use the much cleaner
.clearfix:after { content: ""; display: table; clear: both; }and add theclearfixclass to the element you want self-cleared to keep that CSS to a minimum.