Breaking Down the Dropdown Menu
When creating your website navigation, it might look something like this:
This is a great start. For this technique to work, you will need to nest another
<ul> element inside one of the existing
<li> elements. If you are modifying the above code, it could look something like this:
All-new Echo (2nd Gen) has a new speaker, new design, and is available in a range of styles including fabrics and wood veneers. Echo connects to Alexa to play music, make calls, set music alarms and timers, ask questions, control smart home devices, and more—instantly.
Now For the CSS
That’s all the HTML you need. Simple, right? Trouble is, in the above code, the dropdown menu will be visible and may potentially be messing up your top level navigation. Luckily for you, some quick additions to your CSS can fix this issue.
With CSS, you will be able to hide the dropdown menu and make it visible only when a visitor hovers over the appropriate
Again, that’s it! With this code, you have a horizontal navigation with functioning dropdown menus. A few items of note here are the way the dropdown menu is positioned and the way the hover works. In order for the dropdown menu to become visible on hover without effecting other elements on the page when it does, the positioning has been set to
Also, typically when you add
:hover to an element, it is that element which will receive the change specified. You don’t want that in this case, you want the hover on the
<li> element to trigger a change in the nested
<ul> instead. That is what that
> is for on this line:
nav li:hover > ul. What is being stated here is that when a
<li> is hovered over, trigger the
<ul> inside of it.
This is all the code you need to create your dropdown menus. Not only is it quick and simple, but it’s also going to work for you in older browsers.
You can see the fiddle for this code here.