user3015514
user3015514

Reputation: 21

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{
}

Upvotes: 1

Views: 4784

Answers (5)

Benjamin Pozo
Benjamin Pozo

Reputation: 1

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.

    Upvotes: 0

    Thomas Cheney
    Thomas Cheney

    Reputation: 388

    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.

    Upvotes: 1

    sensei
    sensei

    Reputation: 7592

    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;
    }
    

    Upvotes: 0

    Michał Tabor
    Michał Tabor

    Reputation: 2467

    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?

    Upvotes: 0

    jmore009
    jmore009

    Reputation: 12933

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

    Upvotes: 1

    Related Questions