htmlcsssubmenu

CSS - How can I push the submenus to the left?


I have created a horizontal menu with a horizontal submenu. Though I want all the submenus to be pushed to the left, just like the first submenu. How can I do that? I'm very (very) new to CSS.

I have this HTML code:

<div id="menu">
        <ul>
            <li><a href="#nogo">Link 1</a>
                <ul>
                    <li><a href="#nogo">Link 1-1</a></li>
                    <li><a href="#nogo">Link 1-2</a></li>
                    <li><a href="#nogo">Link 1-3</a></li>
                </ul>
            </li>
            <li><a href="#nogo">Link 2</a>
                <ul>
                    <li><a href="#nogo">Link 2-1</a></li>
                    <li><a href="#nogo">Link 2-2</a></li>
                    <li><a href="#nogo">Link 2-3</a></li>
                </ul>
            </li>
            <li><a href="#nogo">Link 3</a>
                <ul>
                    <li><a href="#nogo">Link 3-1</a></li>
                    <li><a href="#nogo">Link 3-2</a></li>
                    <li><a href="#nogo">Link 3-3</a></li>
                </ul>
            </li>
        </ul>
    </div>

And I have this CSS code:

    #menu{
padding:0;
margin:0;
overflow:hidden;
height:60px;
}
#menu ul{
padding:0;
margin:0;
}
#menu li{
position: relative;
float: left;
list-style: none;
margin: 0;
padding:0;
}

#menu li a{
width:100px;
height: 30px;
display: block;
text-decoration:none;
text-align: center;
line-height: 30px;
background-color: black;
color: white;
}

#menu li a:hover{
background-color: red;
}

#menu ul ul{
position: absolute;
top: 30px;
visibility: hidden;
width: 600px;
}

#menu ul li:hover ul{
visibility:visible;
display: inline;
}

Solution

  • Remove position: relative from #menu li and add it to #menu ul instead. Also add left: 0 to #menu ul ul:

    #menu ul {
      padding: 0;
      margin: 0;
      position: relative; /* add this */
    }
    
    #menu li {
      /* position: relative;   //remove this */
      float: left;
      list-style: none;
      margin: 0;
      padding: 0;
    }
    
    #menu ul ul {
      position: absolute;
      left: 0; /* add this */
      top: 30px;
      visibility: hidden;
      width: 600px;
    }
    
    

    Working example: http://jsfiddle.net/WJN4G/