tags:

views:

215

answers:

3

This is one problem I always have when i'm fixing layouts. I've got a absolutely positioned DIV, I place a child-DIV inside which also needs to be absolutely positioned. But I really want this child-DIV to behave relative to the parent... Is this even possible? Or do I need to create a wrap-DIV?

<div class="container" style="position:relative;">
    <div class="parent" style="position:absolute;">

        <!-- this child div will behave relative to .container -->
        <div class="child" style="position:absolute;"></div>
    </div>
</div>

This is the 'wrapping' solution which I'd rather avoid:

<div class="container" style="position:relative;">
    <div class="parent" style="position:absolute;">
        <div class="wrapper" style="position:relative;">

            <!-- this child div will behave relative to .wrapper-->
            <div class="child" style="position:absolute;"></div>
        </div>
    </div>
</div>
A: 

You might want to ask yourself if you really need to use multiple, nested absolutely positioned elements.

Otherwise, it might be best to go for the wrapper solution.

Bryan Migliorisi
+1  A: 

If you're already absolutely positioning one div, can't you just add the two offsets together for the child? e.g. for #one to be at 10,10 and #two at 10,10 relative to #one,

#one {
    position: absolute;
    left: 10px;
    top: 10px;
}

#two {
    position: absolute;
    left: 20px;
    top: 20px;
}

Or is it something fancier, like #one locking to top-left corner and #two to bottom-right of #one, in which case basic math doesn't work that way? In that case, an extra div is probably necessary.

Or am I just tired and missing something?

Matchu
+1  A: 

An absolutely positioned element is positioned with respect to the edges of its nearest ancestor that is not positioned (i.e. not position: static).

Since the parent element is position: absolute, the child will be positioned with respect to its edges.

So you appear to be asking how to get behaviour you already have. The comment in your first example appears to be incorrect.

David Dorward