开发者

problems with parent absolute positioning

The only element in my html page that has a style of position: relative; is the body.

Inside the body is:

<div id="nav" style="position:absolute;top:275px;left:50%;margin-left:-350px;">
    <div>foo</div>
    <div>bar</div>
</div>

the #nav and #nav div css have a style of position: absolute;

so the #nav div app开发者_开发技巧ears in the middle of the page.

now because the body is relative, and is the ONLY relative element, a style of left:0 on the #nav div elements (the "foo" and "bar") should position the elements 0 pixels to the left of the body. But unfortunately the foo and bar get positioned 0 pixels to the left of the #nav Element. Why is this?

I was under the impression that elements with position relative are treated as the "parent" in positioning terms therefor the foo and bar elements should be positioned 0 pixels to the left of the body.

If this is not correct, would anybody know how to position the elements in such a way?

if my assumption is correct then can somebody tell my why in my case this is not working.

Thanks, Alex


Absolute positioning works relative to the nearest positioned parent element, when that positioning value is relative, absolute or fixed.

This means that in your case the behaviour is correct. div#nav is the first positioned parent of div#nav div because of the absolute positioning. If you want those divs to position relative to the body edge, you will have to take them out of div#nav.


This is correct because when you precise a position (absolute or relative or fixed), all children refer to this element. In your case, as nav is abolute positioned, each div inside nav are relative positioned regarding nav position.

Workarounds :

  • externalize your nav children outside nav
  • do not absolute position "nav"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜