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

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

问题描述

我正在开发一个浏览器游戏.到目前为止,我一直在使用所有位置绝对值.因此,我必须自己设置每个页面的高度.现在试图通过这个问题,但由于我在我的一切中使用绝对位置,它总是阻止浏览器计算正确的 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 高度的总和.目前无论我尝试什么都失败了.如果我将高度设置为自动,并且如果我将主 div 的高度设置为 100%,它计算的高度为 1 像素,则计算为 557 像素.

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 解决方案.

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

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