简体   繁体   中英

CSS absolute positioning in the parent and child

I understand that by setting the parent div to position:relative , if I make the position of the child absolute, than the child's position will be absolute within the parent. If I want to make the grandchild positioned absolutely within child, how would I do that, since child is already set to position:absolute ? Sorry if this question is weird, any help appreciated.

HTML:

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

CSS:

#parent{
position:relative;
}
#child{
position:absolute;
}
#grandchild{
}

why would you need to put another div inside the child? Just absolute position that one and use z-index to layer them

An absolute position element is positioned relative to it's parent element (except if parent has position set to static, but it's not your case), then:

#grandchild{
    position: absolute;
}

will set grandchild's position absolute in relative to child - just as you want?

This is easy, if you want to manipulate more. I made you an example of positioning.

Here is jsfiddle example: http://jsfiddle.net/Be84P/1/

#parent{
position:relative;
height:200px;
background: blue;
}
#child{
position:absolute;
top: 20;
width:20px;
height:100px;
background: red;
}
#grandchild{
position:absolute;
bottom:0;
height: 50px;
background: yellow;
}

You can have more than one 'position:absolute;'in nested elements without regard to the positioning of the parent element. Each time you use absolute, you set that divs position relative to the dimensions of its parent element. The parent element can be relative, absolute, or fixed (anything but static) and it should not affect its children nodes.

I mention this just so that you do not mistakenly think that the relative positioning of #parent has any bearing on the absolute positioning of #child, and the #grandchild element can be positioned as absolute OR relative, just keep in mind that you are positioning it to the dimensions of the #child, and in reference to its immediate parent.

The short answer, set #grandchild{position:absolute;} and it will work just fine.

I believe it does vary on what type of project your working on, but layering or making a list out of it might help. z-index: in CSS, or an ordered list,

    in HTML.

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM