Absolute positioning and its parent element

北城余情 提交于 2019-11-30 09:29:47

It falls back to the nearest ancestor element that has position defined as relative, absolute, or fixed -- not just relative, but any value other than static (the default).

Generally, you'd want to position the item absolutely according to a grid established by its parent. However, sometimes it makes sense to have it positioned to a grid established by a higher up element.

For example:

HTML

<body>
    <div id="div1">
        <div id="div2-A">[some content]</div>
        <div id="div2-B">
            <div id="div3">[more content]</div>
        </div>
    </div>
</div>

CSS

#div1{
    width:1024px;margin:auto;
    position:relative
}
#div3{
    position:absolute;
    bottom:0px; left:0px;
}

In this case, div3 will be positioned all the way to the left & bottom of div1 -- its grandfather -- because its immediate parent (div2) has the default position:static, and so does not establish as an absolute positioning context/grid for its children. But div3 will not (necessarily) go all the way to the left of the viewport or the page body because the next higher up element (div1) has position defined as relative.

UPDATE
In the case you provided (http://purecssmenu.com/), the position:relative declaration is being applied on the :hover pseudo-class, so you won't see it immediately in the styles listed for Google Developer Tools or Firebug.

You can inspect this in Google developer tools by inspecting the parent element, then in the right-hand side of the "Styles" panel, click the "Toggle Element State" button, (looks like a box with dotted border and an arrow pointing in it), then check the box next to ":hover". I'm sure Firebug has something similar.

You'll see this declaration added to the list:

ul.cssMenu li:hover { position: relative; }

This works because when you're not hovering on the parent <li>, the sub-menu <ul> is hidden with display:none, so it doesn't matter where it's positioned.

Another note on the nearest ancestor when an element is being positioned.

Three years later after the OP, CSS3 properties like transform are more widely being used, which implicitly creates a new containing block, forcing the element to have position: relative/absolute;

So to make sure intermediary parent elements have no effect in the positioning of a child element, you need check it has position: static and no transforms set.

Example

    <div id="one">
      <div id="two">
        <div id="three"></div>
      </div>
    </div>
    #one {
      position: relative;
    }
    #two {
      position: static;
      transform: none;
    }
    #three {
      position:absolute;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!