CSS Dropdowns

CSS Dropdowns


CSS Dropdown Menu
Let us now create a dropdown menu - 
Let’s use relative and absolute positioning to create a dropdown menu.
Initially, it’ll be a simple rectangle, but when the user hovers the mouse over it, it pops open a list of links.
We will understand the dropdown menu using an example
The coming example shows the markup for this menu. 
Append it to your HTML after the closing of the
element. This code includes a container that you’ll use to center the content and align it with the banner’s content. I’ve also added an
below the popup to illustrate how the popup appears in front of other content on the page.
Example - 
HTML - 
<div class="container">
<nav>
<div class="dropdown">
<div class="dropdown-label">Main Menu</div>
<div class="dropdown-menu">
<ul class="submenu">
<li><a href="/">Home</a></li>
<li><a href="/coffees">Coffees</a></li>
<li><a href="/brewers">Brewers</a></li>
<li><a href="/specials">Specials</a></li>
<li><a href="/about">About us</a></li>
</ul>
</div>
</div>
</nav>
<h1>Wombat Coffee Roasters</h1>
</div>
The dropdown container includes two children: the label, a gray rectangle that’s always visible, and the dropdown menu that will show and hide as the dropdown is opened and closed. 
The dropdown menu will be absolutely positioned so it doesn’t shift around the layout of the page when it’s revealed. 
This means it appears in front of other content when it’s visible. 
Next, you’ll apply relative positioning to the dropdown container. This establishes the containing block for the absolutely positioned menu. Add these styles to your stylesheet
CSS - 
.container {
width: 80%;
max-width: 1000px;
margin: 1em auto
}
.dropdown {
display: inline-block;
position: relative;
}
.dropdown-label {
padding: .5em 1.5em;
border: 1px solid #ccc;
background-color: #eee;
}
.dropdown-menu {
display: none;
position: absolute;
left: 0;
top: 2.1em;
min-width: 100%;
background-color: #eee;
}
.dropdown:hover .dropdown-menu {
display: block;
}
.submenu {
padding-left: 0;
margin: 0;
list-style-type: none;
border: 1px solid #999;
}
.submenu > li + li {
border-top: 1px solid #999;
}
.submenu > li > a {
display: block;
padding: .5em 1.5em;
background-color: #eee;
color: #369;
text-decoration: none;
}
.submenu > li > a:hover {
background-color: #fff;
}
Output - 
Explanation - 
Now we will see what we have done in css part - 
 


 
 
Now, when you move your mouse pointer over the Main Menu label, the dropdown menu pops open beneath it.
Notice that you used the :hover state of the whole container to open the menu. 
This means that as long as the cursor remains over any of its contents—either the dropdown-label or the dropdown-menu—the menu remains open.