Search code examples
csspositionheightabsolute

Position absolute prevents browser to calculate correct height. Is it possible to fix this issue


I am developing a browser game. Until now i was using all position absolute. Because of that i have to set every page height myself. Now trying to pass this problem but since i used position absolute at my everything it always prevent browser to calculate correct height of div.

Is it possible to achieve this. I mean for example i have div and inside many divs which uses position absolute feature. So i want this main div to calculate its height automatically which would be sum of nested divs height. Currently whatever i tried failed. It calculates the height as 1 px if i set height auto and if i set height 100% of main div it calculates as 557 px.

Thank you.


Solution

  • No, it is not possible through pure CSS to make a parent element automatically resize to contain all of its positioned children.

    Edit: You asked if it was possible with jQuery. It is, if you know whenever any of the children change. This code assumes the parent is an offset parent (that is, it also has position set to something other than static):

    // element is a jQuery object
    var max=0;
    element.children().each(function(index, child) {
        child=$(child);
        var childPos=child.position();
        var childMax=childPos.top+child.outerHeight();
        if(childMax>max) {
            max=childMax;
        }
    });
    element.css({height: max+'px'});
    

    Try the jQuery solution on JSFiddle.