绝对位置会阻止浏览器计算正确的高度。是否可以解决这个问题
我正在开发一个浏览器游戏。到目前为止,我一直在使用所有绝对位置。因此我必须自己设置每个页面的高度。现在试图解决这个问题,但由于我在所有事情上都使用了绝对位置,它总是阻止浏览器计算 div 的正确高度。
是否有可能实现这一点。我的意思是,例如我有 div 和内部许多使用位置绝对功能的 div。所以我希望这个主 div 自动计算它的高度,这将是嵌套 div 高度的总和。目前我尝试的一切都失败了。如果我设置高度自动,它会将高度计算为 1 像素,如果我将主 div 的高度设置为 100%,它会计算为 557 像素。
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,不可能通过纯 CSS 使父元素自动调整大小以包含其所有定位的子元素。
编辑:您询问 jQuery 是否可以实现。确实如此,如果你知道孩子们何时发生变化的话。此代码假定父级是偏移父级(即,它的
position
也设置为static
以外的值):在 JSFiddle 上尝试 jQuery 解决方案。
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 thanstatic
):Try the jQuery solution on JSFiddle.
您必须了解
Position:absolute
将 div 置于正常流程之外。这意味着即使一个 div 位于另一个 div 内,当它被渲染时,它也会在所有 div 之外。因此,您无法计算“内部”的内容,因为它们实际上是“外部”的。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".您可以使用 CSS 来读取位置。我觉得你正在尝试使用 CSS 来计算顶部和左侧,如下所示:
但是你应该依赖浏览器计算的偏移量。要读取准确的正确位置,请使用
offsetTop
和offsetLeft
CSS left 值与 offsetLeft 不同的原因是 CSS left 是元素最左边缘与其第一个 < 之间的空间量。 em>相对父级离开浏览器边缘。
如果您更喜欢使用 jQuery,那么有两种 jQuery 方法可以为您提供位置。一种是
.position()
,一种是.offset()
。 offset 是适合您的选择。You may using CSS to read position. I feel you are trying to calculate top and left using CSS like this:
But you should rely on offset that browser calculates. To read the exact correct position use
offsetTop
andoffsetLeft
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.