Page Widget How to - Create two level navigation bar with dropdown








Question

We would like to know how to create two level navigation bar with dropdown.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
ul {<!--   w  ww  . j  a  v a2  s .com-->
  float: left;
  padding: 0;
  margin: 0;
  list-style: none;
}

.menuList {
  float: left;
}

.menuItem {
  display: block;
  width: 100px;
  height: 25px;
  padding: 10px;
  background-color: #EEE;
  color: white;
  text-decoration: none;
  text-align: center;
}

a:hover {
  background-color: orange;
}

.menuLevel1 {
  display: none;
}

.subMenu1 {
  display: block;
  position: relative;
}

.itemLevel1 {
  display: block;
  width: 120px;
  height: 25px;
  background-color: #EEE;
  text-align: center;
  padding: 10px;
  text-decoration: none;
  position: relative;
}

li:hover ul.menuLevel1 {
  display: block;
  position: absolute;
}

.menuLevel2 {
  display: none;
}

.itemLevel2 {
  display: block;
  width: 120px;
  height: 25px;
  background-color: #EEE;
  text-align: center;
  padding: 10px;
  text-decoration: none;
}

.menuLevel1 li:hover ul.menuLevel2 {
  display: block;
  position: absolute;
  left: 100%;
  top: 0;
}
</style>
</head>
<body>
  <nav>
    <ul>
      <li class="menuList"><a href="#" class="menuItem">Menu 1</a></li>
      <li class="menuList"><a href="#" class="menuItem">Menu 2</a>
        <ul class="menuLevel1">
          <li class="subMenu1"><a href="#" class="itemLevel1">Sub menu 1</a></li>
          <li class="subMenu1"><a href="#" class="itemLevel1">Sub menu 2</a>
            <ul class="menuLevel2">
              <li class="subMenu2"><a href="#" class="itemLevel2">Sub Sub menu 1</a></li>
              <li class="subMenu2"><a href="#" class="itemLevel2">Sub Sub menu 2</a></li>
              <li class="subMenu2"><a href="#" class="itemLevel2">Sub Sub menu 3</a></li>
            </ul></li>
          <li class="subMenu1"><a href="#" class="itemLevel1">Sub menu 3</a>
            <ul class="menuLevel2">
              <li class="subMenu2"><a href="#" class="itemLevel2">Sub Sub menu 1</a></li>
              <li class="subMenu2"><a href="#" class="itemLevel2">Sub Sub menu 2</a></li>
              <li class="subMenu2"><a href="#" class="itemLevel2">Sub Sub menu 3</a></li>
            </ul></li>
        </ul></li>
      <li class="menuList"><a href="#" class="menuItem">Menu 3</a></li>
    </ul>
  </nav>
</body>
</html>

The code above is rendered as follows: