tags:

views:

29

answers:

2

Hi,

I'd like to position a div on top of another div, but absolutely, something like:

<div id='parent'>

   <div id='under' z-index='1' width='100' height='100'></div>

   <div id='over' z-index='2' width='100' height='100'></div>

</div>

I know the width and height I need the two divs to be, but I don't know what absolute position they should be (if I read correctly, we need to specify absolute positioning for divs using z-index. Since they're both in a parent div, can I just set the x/y positions to both be 0,0, so that they're just absolutely positioned relative to their parent? Ehh, probably not - what can I do here?

Thanks

+1  A: 

You just need to swap the order, so the absolute one comes first, like this:

<div id='parent'>
   <div id='over' style='position: absolute; width: 100px; height: 100px'></div>
   <div id='under' style='width: 100px; height: 100px'></div>
</div>

You can try a demo here, notice the result is red (the #over style).

This is over-top because the first one starts at the same position in the flow as the second, but takes up no room in the flow because of it being absolute. This means the under div also starts at the exact same position.

Nick Craver
ok that works brilliantly, thanks.
+1  A: 

Well, the key words are 'relative to their parent', meaning that the parent should have relative positioning (position: relative;) in order to contain the absolutely positioned child divs, otherwise they'll be absolutely positioned relative to the document window.

After, you've set the parent's position to relative, set the child divs' position to absolute and by default, they should overlap at (0,0) relative the parent's position. You can then specify even more by adjusting the values for the properties: top, right, bottom, left.

Gio Borje
This is only true if you actually give the element a `top` or `left` position :) There's no need for that in this case though, just put the absolute one just before the one it overlays, document flow and absolute being above normal flow takes care of the rest.
Nick Craver