CSS Dropdowns allow users to access additional options or information by hovering or clicking on a navigation item. They are commonly used in navigation menus, submenus, and forms.
To create a dropdown menu, you can use the CSS display
property and set it to none
for the dropdown content. Then, use a pseudo-class such as :hover
or :focus
to display the content when the user interacts with the navigation item.
Here is an example of a CSS dropdown menu:
HTML:
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li class="dropdown">
<a href="#">Dropdown</a>
<ul class="dropdown-content">
<li><a href="#">Option 1</a></li>
<li><a href="#">Option 2</a></li>
<li><a href="#">Option 3</a></li>
</ul>
</li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
CSS:
nav ul {
list-style: none;
margin: 0;
padding: 0;
}
nav li {
display: inline-block;
margin-right: 20px;
position: relative;
}
nav li a {
color: #333;
display: block;
padding: 10px;
text-decoration: none;
}
.dropdown-content {
display: none;
position: absolute;
top: 100%;
left: 0;
z-index: 1;
}
.dropdown:hover .dropdown-content {
display: block;
}
In this example, the ul
element is styled with list-style: none
, margin: 0
, and padding: 0
to remove default list styling. Each li
element is set to display: inline-block
and margin-right: 20px
to create horizontal navigation items with a bit of space between them. The position: relative
property is also set on each li
to allow for absolute positioning of dropdown content.
The dropdown content is created with a nested ul
element with the class dropdown-content
. It is set to display: none
and positioned absolutely with top: 100%
and left: 0
. The z-index: 1
property ensures that it appears on top of other content. Finally, the dropdown content is displayed when the user hovers over the parent li
element with the class dropdown
using the :hover
pseudo-class.