2

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.

Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
Furkan Gözükara
  • 22,964
  • 77
  • 205
  • 342
  • 2
    An absolutely positioned element is *removed from the flow of the page*. The *expected* behavior is that an element completely ignores the height of that absolute element when determining its own height. – animuson Sep 10 '11 at 02:37
  • yes i read but it was not what was asking. thank you though :) – Furkan Gözükara Sep 10 '11 at 03:06

3 Answers3

6

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.

icktoofay
  • 126,289
  • 21
  • 250
  • 231
2

You have to understand that Position: absolute takes the div outside of it's normal flow. That means that even if a div is within another div, when it's rendered it's outside of all of them. Therefore, you can't calculate what's "inside", because they're effectively "outside".

Erik Funkenbusch
  • 92,674
  • 28
  • 195
  • 291
1

You may using CSS to read position. I feel you are trying to calculate top and left using CSS like this:

documnent.getElementById('theDiv').style.left;

But you should rely on offset that browser calculates. To read the exact correct position use offsetTop and offsetLeft

documnent.getElementById('theDiv').offsetLeft; //gives you right number.

The reason CSS left value would be different from offsetLeft is CSS left is amount of space between elements very left edge and its first relative parent left not browsers edge.

if you prefer using jQuery then there is two jQuery methods that gives you position. One is .position() and one is .offset(). offset is the right one for you.

Mohsen
  • 64,437
  • 34
  • 159
  • 186