绝对位置会阻止浏览器计算正确的高度.是否可以解决此问题 [英] Position absolute prevents browser to calculate correct height. Is it possible to fix this issue

查看:100
本文介绍了绝对位置会阻止浏览器计算正确的高度.是否可以解决此问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发浏览器游戏.到目前为止,我使用的是绝对位置.因此,我必须自己设置每个页面的高度.现在尝试传递此问题,但是由于我在所有操作中都使用绝对位置,因此始终会阻止浏览器计算div的正确高度.

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.

是否有可能实现这一目标.我的意思是,例如,我有div,并且在许多使用位置绝对功能的div中.所以我希望这个主div自动计算其高度,该高度将是嵌套div高度的总和.目前,无论我尝试了什么,都失败了.如果我将height设置为auto,则将高度计算为1 px;如果将main div的高度设置为100%,则它将计算为557 px.

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.

谢谢.

推荐答案

否,不可能通过纯CSS来使父元素自动调整大小以包含其所有已定位子元素.

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

编辑:您询问是否可以使用jQuery.是的,如果您知道每一个孩子都变了.此代码假定父级是偏移父级(即,它还将position设置为除static之外的其他值):

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'});

在JSFiddle上尝试jQuery解决方案.

Try the jQuery solution on JSFiddle.

这篇关于绝对位置会阻止浏览器计算正确的高度.是否可以解决此问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆