Floating div element

position: absolute with a high enough z-index:

#element {
    position: absolute;
    top: 50px;
    left: 200px;
    z-index: 10;
}

This is a follow up to Tatu's answer, which will work, but uses z-indexes in a clumsy, but very common, way.

Z-index determines the stacking order of positioned elements, relative to other positioned elements. The stacking order is also relative to the stacking order of the parent elements. So:

When you have two sibling elements in a page:

<body>
    <div style="position:absolute;z-index:2"></div><!-- Position 2 (top) -->
    <div style="position:absolute;z-index:1"></div><!-- Position 1 (bottom) -->
</body>

These are both stacked according to their parent - the body, which is at its default 'bottom' of the stack.

Now, when these elements have children with z-indexes, their position in the stack is determined relative to their parents' position:

<body>
    <div style="position:absolute;z-index:2"><!-- Position 2 (top) -->
         <div style="position:absolute;z-index:2"></div><!-- Position 2.2 -->
         <div style="position:absolute;z-index:1"></div><!-- Position 2.1 -->
    </div>
    <div style="position:absolute;z-index:1"><!-- Position 1 (bottom) -->
         <div style="position:absolute;z-index:2"></div><!-- Position 1.2 -->
         <div style="position:absolute;z-index:1"></div><!-- Position 1.1 -->
    </div>
</body>

I find it useful to think of the children as having a 'point' z-index - so the child of an element with z-index:1 has a z-index of 1.x. This way, you can see that, even if I give this div a z-index of 100000, it will never appear on top of an element with the parent z-index of 2. 2.x always appears on top of 1.x

This is useful when you're making 'floating' things like overlays, post-it notes, etc. A setup like this is a good start:

<body>
    <div id="contentContainer" style="position:relative;z-index:1">
        All your 'page level content goes here. You can use all the z-indexes you like.
    </div>
   <div id="overlayContainer" style="position:relative;z-index:2">
        Anything to float 'on top of the page' goes here. Nothing inside 'contentContainer' can ever appear on top of it.
    </div>
</body>

Anything you want to float on top goes into 'overlayContainer' - the base z-indexes keep the two 'layers' separate, and you can avoid using confusingly high z-indexes like 999999 or 100000.


Yup, you need your CSS to look something like this

.floating-div {
  position: absolute;
  left: 40px;
  top: 40px;
  z-index: 100000;
}