Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

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

I have div which hosts another div. Ok, I get the case when the parent is position:relative and the child is position:absolute. I don't get what happens when

  1. parent's position is absolute and child's position is relative
  2. parent's position is absolute and child's position is absolute
  3. parent's position is relative and child's position is relative

I use the JSbin example from Why does an absolute position element wrap based on its parent's right bound? but the question applies to positioning concept in general

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 its 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 its own position. It's just saying to its 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 its 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...