Search code examples
htmlcssdrop-down-menuprogram-entry-pointoverlap

How to get a html element to overlap another when it is displayed?


#nav ul ul li {
    display: block;
    font-color: blue;
    font-size: 1.5em;
    z-index: 1;
    position: relative;
}

Current output For example, I have a mobile responsive site, and the main menu works fine, but when I resize the browser window to be small, to replicate a small screen such as a mobile phones.... One of the main menu items that has a drop down list gets displayed on top of the other main menu items. This means that the main menu drop down items are displayed on top of some main menu text directly underneath!

I have done z index so the drop down menu does sit on top, but the problem is, even though it sits on top, the main menu underneath is still displayed.

This is the jsfiddle


Solution

  • When you don't set z-index, elements follow a default ordering for which gets displayed on top:

    When no element has a z-index, elements are stacked in this order (from bottom to top):

    1. Background and borders of the root element
    2. Descendant blocks in the normal flow, in order of appearance (in HTML)
    3. Descendant positioned elements, in order of appearance (in HTML)

    MDN

    In your HTML, the ul for the submenu appears before the HTML for the other menu items, and so the other menu items appear on top of the submenu's background.

    To fix this, set a z-index so that the background of the ul will be promoted:

    #nav ul ul {
      z-index: 1;
    }
    

    Fixed JSFiddle