On many websites, we can see how in a navigation menu with many links, when you hover over or click on some of these elements, a container with other links unfolds. This is known as a dropdown menu. Below, you will learn how to create it simply using only HTML and CSS.
HTML structure for our dropdown menu
<nav><ul class="main-links"><li>Item 1</li><li>Item 2</li><li>Item 3</li><li class="dropdown-li">Dropdown Item<ul class="dropdown"><li>Item</li><li>Item</li><li>Item</li></ul></li></ul></nav>
In this HTML structure, we have a "nav" that, in this case, acts as a container for the elements. Next, there's a "ul" element with the class "main-links" containing various list items (li). The fourth item, which will serve as the container for the dropdown elements, has the class "dropdown-li."
Finally, within this "dropdown-li" element, we add another "ul" element with different "li" items that will appear when hovered over.
Making the entire menu horizontal using Flexbox
.main-links {display: flex;gap: 1rem;list-style: none;}
CSS Styles to Make the Dropdown Menu Appear
A dropdown menu wouldn't be a dropdown if it didn't hide and appear. Next, we apply the styles to make the rest of the elements expand when hovered over.
.main-links li {padding: 0.5rem 1rem;background-color: rgb(10, 207, 197);}.dropdown-li {position: relative;}.dropdown-li:hover .dropdown {display: block;opacity: 1;}.dropdown {background-color: slateblue;margin: 0;padding: 0;width: 100%;position: absolute;left: 0;top: 100%;opacity: 0;display: none;background: red;}.dropdown li {list-style: none;}
Try the dropdown menu for yourself.
I am Juneiker Castillo, a passionate front-end web developer deeply in love with programming and creating fast, scalable, and modern websites—a JavaScript enthusiast and a React.js lover ⚛️.
About me