Search code examples
htmlcsspositionabsolute

Div with position absolute does not behave as it should


I am having trouble with the design of a simple menu in the header of an html document. In this reduced version, the menu is supposed to have three items next to each other (horizontally) and a fourth item directly under the third. So I ensure that at least the third item has relative positioning and the container that wraps the fourth item has absolute positioning with left: 0. So far, everything works as expected.

However, when I put an tag around the fourth item, this item moves to the very left of the screen, along with its surrounding container. Why is that, and what can I do against it? I need that tag.

The following fiddle shows the situation before including the tag: https://jsfiddle.net/Marconi_1900/uocmvrb0/7/

Thank you for your help.

I tried to surround the fourth item with an unordered list tag, making the fourth item the first on that list. It did not help, though.


Solution

  • You should be able to add additional markup, just make sure it is inside your #dropdown container.

    #third {
      position: relative;
    }
    #dropdown {
      position: absolute;
      width: 100px;
      left: 0;
    }
    #dropdown ul {
      border: 1px solid red;
      padding: 0;
    }
    #dropdown ul li {
      list-style: none;
    }
    <!DOCTYPE html>
    <html lang="en">
       
    <header>
      <nav >
          <a>First item</a> 
          <a>Second item</a>
          <a id="third">Third item
            <div id="dropdown">
              <ul>
                <li>AAA</li>
                <li>BBB</li>
                <li>CCC</li>
              </ul>
            </div>     
          </a>
      </nav>
    </header>
    
    </html>