css - parent's position is absolute and child's position is relative and vice versa

僤鯓⒐⒋嵵緔 提交于 2019-11-29 02:28:46

Read more about absolute, relative, and fixed position and how they differ here, but I'll try to answer your question about relationships specifically.

position: absolute will position that element to it's nearest parent with a position other than static. Static is the default for everything.

position: relative is a little weird because it really affects that element's children, not it's own position. It's just saying to it's child elements, "position yourself relative to me if you have position: absolute." A position of fixed or absolute does the same thing (meaning its positioned children will position themselves relative to its boundaries), but these styles also affect their own position on the page. An element with position: relative won't look any different, but it's children might.

So consider a situation like this:

<div class="parent">
     <div class="child">
           <div class="grandchild"></div>
     </div>
</div>

If grandchild has position: absolute, it will position itself relative to the browser window because there is no parent with a position other than the default of static.

If parent also has position of relative, absolute, or fixed, grandchild will position itself relative to the boundaries of parent.

However, if child also has a position of relative, absolute, or fixed, the grandchild will position itself relative to child's boundaries, because it is the nearest parent with a position other than static.

In summary, relative affects an element's children, while absolute and fixed affect the element itself as well as its children.

And remember that position: fixed bypasses all relative and absolute parents and always positions itself relative to the browser window.

1 - if the mommy is relative and the child is absolute : the mommy listens to her child. as if to protect him. sort of.. 2 - if they are both absolute : they have nothing to do with eachother. they are strangers to eachother. 3 - if the parent is absolute and child relative : they are bound. the child moves ( width and height ) towards or away from his mommy.

It will always be a little strange, there are a lot of great texts about this, but also for me it is always just switching absolute and relative until it works. hope this cleares it up a little.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!