Search code examples
csslistmenuz-index

CSS and z-index: child element under parent element in a list


I am working on a layout for a webshop and am experiencing a problem which seems to be very specific.

There is a dropdown navigation which is design to look kind of a tab with a box under it. The point is, that there is a 1px border line between the tab (first level Menu Item) and the box (second level items) which I can't hide.

I thought about giving the second level box a lower z-index than the first level element, but that didn't changed anything. I read a lot about z-index, how it works and how it NOT works, but nothing was about z-index within one list.

This is how it should looks like and how it really looks like: https://i.sstatic.net/xbQ6x.png

I created a codepen, which shows the problem very good, when hovering the first level items: http://codepen.io/anon/pen/bNqJxN

li .dropdown{
            overflow: hidden;
            position: relative;
            display: inline;
            visibility: hidden;
            position: absolute;
            padding:0;
            margin: 0 0 0 -1px; /*Putting a negativ margin-top here puts the box OVER the parent element :-( */
            background: #fff;
            border: 1px solid $light-grey;
            width: 280px;
            height: 200px;
            &.right {
                right: -1px;
                left: auto;
            }
            .dropdown-1-2 {
                float: left;
                width: 50%;
            }
        }

Solution

  • I usually solve this issue with z-index to have the bottom of the li to overlap the top of the dropdown.

    In your case, I had to remove the * selector for the z-index which came after the li and dropdown which was resetting the z-index to 2 on everything in that navigation. Instead I created just the one stacking context (here's an article on it) for the first nav to appear above the second, and then I gave the ul position relative and the dropdown a z-index of -1 and -1px top margin to move it just behind the unpositioned li.

    #mainnav {
        ...
    
        ul {
            @include reduced-list;
            ...
            position: relative;
    
            li .dropdown{
                ...
                margin: -1px 0 0 -1px;
                z-index: -1;
    
                ...
    
            &#nav1 {
                z-index: 2;
            }
            &#nav2 {
                z-index: 1;
            }
    

    Sorry, the codepen didn't save.