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

淺唱寂寞╮ 提交于 2019-12-11 00:25:24

问题


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.


回答1:


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.




回答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".




回答3:


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.



来源:https://stackoverflow.com/questions/7369246/position-absolute-prevents-browser-to-calculate-correct-height-is-it-possible-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!