Bare Bones CSS-based Drop-down

October 4th, 2012

Drop-downs are nothing new at this point. In fact, this trend that started to take off in the late 1990’s has seen many changes and evolution in it’s technology, development and design. Through the use of modern CSS, we are able to ditch the clunky JavaScript, Flash and Applet implementations of yesteryear.

Drop-down menus are extremely prolific, yet, there’s quite a few people that still don’t understand how they work. It’s a question I get a lot. Well, I decided to break it down in to it’s bare essentials for a horizontal navigation with a depth of 2:

Demo

Code

HTML

<ul id="nav">
    <li><a href="#">Test</a></li>
    <li><a href="#">Test Dropdown</a>
        <ul>   
            <li><a href="#">Test Drop</a></li>
            <li><a href="#">Test Dropdown #2</a>
                <ul>
                    <li><a href="#">Test Drop</a></li>
                    <li><a href="#">Test Drop</a></li>
                    <li><a href="#">Test Drop</a></li>
                </ul>
            </li>        
            <li><a href="#">Test Drop</a></li>
        </ul>
    </li>
    <li><a href="#">Test</a></li>
    <li><a href="#">Test</a></li>
</ul>‚Äč

CSS

#nav, #nav li {
    list-style:none;
    display:inline;    
}

#nav ul {
    display:none;    
}

#nav li:hover > ul {
    display: block;
    position: absolute;
    margin-top: -2px;  
}

As you can see, using a basic HTML list with a couple CSS properties, you can get yourself a drop down in no time at all. Of course, most of your time will be spent on the design and layout itself.

What’s the magic the makes it work? Well, it starts off by hiding all the <ul> elements under the main #nav ul, using display:none. This will hide as many sub-menus as you put in your HTML markup with ease. The next part is showing them again when ever you are hovering on any <li> element with <ul> children inside them, selecting it with the special “>” selector. We also move the margin up a little bit to account for any pixels in between the elements. Browsers are usually pretty good for accounting for this gap, but just this is just to make sure your hovers don’t lose focus. You may need to adjust this based on your design.

This entry was posted in Blog and tagged , .

3 Responses to Bare Bones CSS-based Drop-down

Leave a Reply

*

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.

TOP