Position:absolute element being hidden behind later elements

user1684248 picture user1684248 · Oct 19, 2012 · Viewed 44.7k times · Source

I've put together a jsfiddle to illustrate my problem here. Essentially, I've got an absolutely-positioned menu system above my main content, but the content seems to be floating in front of the menus. Hover over "Link 3" to see that it's just the main content that's hiding it; the menus show up below when they're long enough.

My nav-header looks something like this:

<div id='nav-header'>
    <div class='nav-bar'>
        <div class='nav-item '>
            <a class='link-3' href='#'>
                <div class='nav-text-container'><p>Link 3</p></div>
            </a>
            <div class='flydown-container link-3'>
                <div class='flydown'>
                    <div class='header'>Heading 1</div>
                    <ul>
                        <li><a class='secondary-menu-link' href='#'><span>Sub-link 1</span></a></li>
                        <li><a class='secondary-menu-link' href='#'><span>Sub-link 2</span></a></li>
                        <li><a class='secondary-menu-link' href='#'><span>Sub-link 3</span></a></li>
                        <li><a class='secondary-menu-link' href='#'><span>Sub-link 4</span></a></li>
                        <li><a class='secondary-menu-link' href='#'><span>Sub-link 5</span></a></li>
                    </ul>
                    <div class='header'>Heading 2</div>
                    <ul>
                        <li><a class='secondary-menu-link' href='#'><span>Sub-link 1</span></a></li>
                        <li><a class='secondary-menu-link' href='#'><span>Sub-link 2</span></a></li>
                        <li><a class='secondary-menu-link' href='#'><span>Sub-link 3</span></a></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

There's quite a bit of CSS, it's all at that jsfiddle link above.

Answer

Ennui picture Ennui · Oct 19, 2012

Use the z-index CSS property (stacking level). Lower z-index means lower stacking context (so if two overlapping sibling elements have different z-indices, the one with the higher z-index will display on top).

Note that z-index establishes a new stacking context for each level of elements so they need to be on the same level of the DOM. Also, z-index only works on positioned elements so it won't do anything unless you set them to relative, absolute or fixed position.

Fixed your code:

#nav-header {
    width: 940px;
    margin-bottom: 20px;
    position: relative;
    z-index: 2;
}
#upper-section {
    height: 300px;
    font-size: 0;
    position: relative;
    z-index: 1;
}

More z-index info: http://css-tricks.com/almanac/properties/z/z-index/