Dropdown menus are a great way of including a long list of links without cluttering up your page. The issue though is that they can be hard to style, but look quite ugly if you don’t.
I have tried my level-best to keep the code as short & simple as possible. This is built with plain CSS and HTML only. I have not used any library.
Before we begin, let me show you a glimpse of what we are going to create.
Creating the HTML Part
Breaking down the components:
Now we can move along to create the HTML elements.
<nav id="nav-element">
<button id="button-dropdown">Dropdown </button>
<div id="div-products">
<a href="">Product 1 </a>
<a href="">Product 2 </a>
<a href="">Product 3 </a>
<a href="">Product 4 </a>
<a href="">Product 5 </a>
</div>
</nav>
Adding the CSS:
Let us first add CSS to the "nav" tag.
/* <nav> element */
#nav-element {
position: relative;
display: inline-block;
}
Note: In display, Use inline-block as only when we hover in-line, the drop-down appears. Do not use block element, as then the drop-down will appear when we hover around the block.
Adding CSS to the "button" tag.
/* <button> element */
#button-dropdown {
width: 10rem;
margin: auto;
padding: 0.5rem 0rem;
background-color: #3b70ff;
color: white;
border: 1px solid #3b70ff;
}
Adding CSS to "div" tag.
/* <div> element */
#div-products {
display: none;
width: 10rem;
margin: auto;
color: #3b70ff;
border: 1px solid #3b70ff;
}
Note: When creating these components initially, set "display: block", else you will not be able to see the output.
Adding CSS to "a" tag.
/* <a> element */
#div-products a {
display: block;
text-decoration: none;
padding: 0.5rem 0rem;
}
Note: We use "block" as "a" tag is an in-line element ie. the output of all the "a" tags are in the same line.
Hurray! Now you are 95% done with the work. All that is remaining is the hover features. Let us get right into it!
Adding the hover feature:
When we hover over the "nav" element, the display of "div" tag should appear ie. drop-down menu should appear.
#nav-element:hover #div-products {
display: block;
}
Another feature:
When we hover over the "a" elements ie. Product 1, Product 2, etc., we want a change in background color & color of the text.
#div-products a:hover {
background-color: #3b70ff;
color: white;
}
Aaaanddd, we are done. Do try the code and let me know if you found it useful.
Here's a link to the live demo: 71cqf.csb.app
Disclaimer: This is my first blog into the tech space. I am a complete newbie into the web dev world, so if I haven't practiced the best-practices - do let me know & I'll be more than glad to correct myself. :D
I document my journey and experiences on Twitter and LinkedIn.