Skip to content Skip to sidebar Skip to footer

Get Height Of Document Content Including Absolute/fixed Positioned Elements

I need to resize an iframe to match its content, but the height properties I have tried don't account for elements with position: fixed. Assume a document with only two elements wi

Solution 1:

I've found the best way is to use javascript as it can get the height reliably after rendering. In a recent project I did this with jQuery to get full height of the window:

$(document).height()

You could do something like this for element heights:

$('.element2').height($('.element1').height())

Update:

$('iframe').height($('iframe').parent().height())

Solution 2:

The only way I could figure out was to get the actual bottom position of all elements:

var els = Array.prototype.slice.call(document.body.getElementsByTagName('*'));
var elHeights = [];
for (var i = 0, l = els.length; i < l; i++) {
  elHeights.push(els[i].scrollTop + els[i].offsetHeight);
}
var docHeight = Math.max.apply(Math, elHeights);

Browsers managed between 5-100k operations per second on a DOM with 100 elements, and in my case that's about the size most documents will have.


Post a Comment for "Get Height Of Document Content Including Absolute/fixed Positioned Elements"