CSS: flyout menu tutorial

A pure CSS flyout menu is another feature that is always present in every developer's wish list. In this tutorial I'm going to show you how to create a simple but effective CSS flyout menu by following a step-by-step approach. If you're ready, we can get started.

Step 1: The markup

We'll use unordered lists to mark up both the main and the sub-menu. The active list item will have a CSS class on it:

<ul id="navigation">

 <li><a href="#">Home</a></li>
 <li class="sub">
 
  <a href="#">About</a>
 
  <ul>
  
    <li><a href="#">Us</a></li>
    <li><a href="#">Our projects</a></li>
    <li><a href="#">Our mission</a></li>
  
  </ul>
 </li>
 
 <li><a href="#">Contacts</a></li>

</ul>

Step 2: Styling the main menu

We need to select only the very direct children of our navigation element, so we'll use the child selector here:

#navigation {
 width: 15em;
 margin: 0;
 padding: 0;
 list-style: none;
 background: #000;
 color: #fff;
 font: 100% Arial, sans-serif;
}

#navigation > li {
 display: block;
 width: 100%;
}

#navigation > li > a {
 display: block;
 height: 100%;
 padding: 1em;
 font-weight: bold;
 text-transform: uppercase;
 color: orange;
 text-decoration: none;
}

#navigation > li > a:hover {
 background: #c60;
 color: #fff;
}

As you can see, we've created a simple vertical navigation menu here.

Step 3: Styling the sub-menu

Our sub-menu needs to be hidden before a user hovers the active item with the mouse. For that reason, we'll use negative absolute positioning here. Further, since we want that our sub-menu be positioned relatively to the active item, we need to create a contextual positioning on that item by using position: relative:

#navigation > li.sub {
 position: relative;
}

#navigation > li.sub ul {
 margin: 0;
 padding: 0;
 width: 15em;
 list-style: none;
 font: 100% Arial, sans-serif;
 background: #c60;
 color: #fff;
 position: absolute;
 left: -1000em;
}

#navigation > li.sub ul li {
 display: block;
 width: 100%;
}

#navigation > li.sub ul li a {
 height: 100%;
 display: block;
 color: #fff;
 font-size: 1.2em;
 font-weight: bold;
 text-decoration: none;
 padding: 1em;
}

#navigation > li.sub ul li a:hover {
 background: #a40;
}

Now our sub-menu is styled but hidden. We need to show it.

Step 4: Showing the sub-menu

To show the sub-menu, we have only to set the left property to the overall width of our main menu, that is, 15em:

#navigation > li.sub:hover ul {
 top: 0;
 left: 15em;
}

You can see the demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

2 thoughts on “CSS: flyout menu tutorial”

  1. I was about to say it didn't work for me and I didn't know why. Then I realized I hadn't closed my style tag. Oops.

    Great guide.

Leave a Reply

Note: Only a member of this blog may post a comment.