Creating a Slide Drop Down menu using HTML And CSS

Creating a Slide Drop Down menu using HTML And CSS

Creating a menu where the drop downs appear to slide or expand down from the bottom of the parent element is simple, but you have to follow some rules. My first attempt at it was to set the height of the entire drop down ul to height: 0 then transition to height: auto. I quickly found out that this doesn't work as transitions will not work with height: auto. This means that you either need to have a fixed height for all of your drop downs or you have to think of something else. Yes, I know you can use javascript to find the height of each element and then transition to that height but my goal is to not use any javascript. 

STEP 1: HTML

All of the examples use the same markup consisting of a simple unordered list. 

<nav class="nav">
      <ul>
        <li><a class="active" href="#">Home</a></li>
        <li><a href="#">Nav Item</a>
          <ul>
              <li><a href="#">Subnav Item</a></li>
              <li><a href="#">Subnav Item</a></li>
              <li><a href="#">Subnav Item</a></li>
          </ul>
        </li>
        <li><a href="#">Nav Item</a>
          <ul>
              <li><a href="#">Subnav Item</a></li>
              <li><a href="#">Subnav Item</a></li>
              <li><a href="#">Subnav Item</a></li>
          </ul>
        </li>
        <li><a href="">Nav Item</a></li>
        <li><a href="">Nav Item</a></li>
        <li><a href="">Nav Item</a></li>
      </ul>
      <div class="clear"></div>
  </nav>

Step 2: Basic CSS

html,body{
  padding: 0;
  margin: 0;
}
body{
  background-color: rgba(255, 0, 0, 0.5);
}
.clear{
  clear: both;
}

.nav{
  background-color: #fff;
}
.nav ul {
    list-style:none;
    margin:0;
    padding:0;
    z-index: 1;
}

.nav ul li {
    float:left;
    position:relative;
}
.nav a {
    display:block;
    padding:0 20px;
    line-height: 50px;
    color:#000;
    border-left:1px solid #595959;
    text-decoration: none;
    font-family: lato;
    font-weight: bold;
}
.nav a:hover {
    text-decoration:none;
    background:#e7e7e7;
}
/*-- DropDown --*/
.nav li ul {
    background:#fff;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
}
.nav li ul li {
    min-width:200px;
    border-bottom: 1px solid rgba(0,0,0,0.2);
}
.nav li ul a {
    border:none;
}
.nav li ul a:hover {
    background:rgba(0,0,0,0.2);
}

Step 3: Animation Dropdown 

/*-- animation --*/
.nav li ul {
    position:absolute;
    left:0;
    top:49px;
    z-index:-1;
}
.nav li ul li {
    overflow:hidden;
    height:0;
    -webkit-transition:height 200ms ease-in;
    -moz-transition:height 200ms ease-in;
    -o-transition:height 200ms ease-in;
    transition:height 200ms ease-in;
}
.nav ul > li:hover ul li {
    height:50px;
}

See the Pen Pure CSS Slide Drop Down navbar by Rashedul Hasan (@rhsuman) on CodePen.