Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontal, two-level navigation menu in CSS

Tags:

css

I am building a two-level navigation menu for a website. Both levels will always be visible.

My problem: I would like to

  • Have 1st and 2nd level menus horizontal, occupying one line each
  • Left-align the sub-level menu with the currently active 1st-level menu item
  • Not have the sub-level menu push the remaining 1st level menu items to the right

Childlike ASCII art illustration:

AAA BBBBBB CC DDD [1st level, B selected]
    aa bbb ccccc  [2nd level, options of B visible]


CSS:

.nav, .nav ul {list-style-type:none; margin:0; padding:0; float:left;}
.navl ul li ul li {}
.nav {margin-bottom:-1px;margin-right:-1px;}

.nav a {float:left; line-height:16px; padding:4px 0; border:1px solid #fff; margin-bottom:-1px;}

.nav ul {position:relative; clear:left;} 
 .nav ul li {float:left; clear:left;}
.nav a {position:relative;}

.sub-li a {margin-right:0;}

HTML:

<ul class="nav">
    <li><a href="#url">Home</a></li>
</ul>
<ul class="nav">
    <li class="sub-li"><a class="sub-a" href="#url">Library</a>
        <ul>
            <li><a href="#url">Opening hours</a></li>
            <li><a href="#url">Librarians</a></li>
            <li><a href="#url">Geeks</a></li>
        </ul>
    </li>
</ul>
<ul class="nav">
    <li><a href="#url">About us</a></li>
</ul>

In this example, I cannot even get the 2nd level menu horizontal. But I can already see that long titles in the 2nd level menu push the last "about us" 1st level menu item out to the right, which looks ugly.

Any help is greatly appreciated!

like image 478
PeerBr Avatar asked Apr 18 '26 05:04

PeerBr


1 Answers

The key to not pushing the 1st level nav over is to put position: absolute; left: 0; on the 2nd level nav. You'll have to add position: relative; to li.sub-li

like image 54
joeljoeljoel Avatar answered Apr 21 '26 22:04

joeljoeljoel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!