Is it possible to create a dropdown menu using only CSS, similar to what you would find in most applications? I have a simple menu bar at the top of my screen and I want to be able to hover over an item like "Item1" and see sub-items appear below it.
I envision the dropdown menu as a complete feature that allows me to easily add new menu items through HTML or CSS. The main purpose of this menu is for users to click on an option (e.g. "Author") and then view a list of related items (e.g. Books) associated with that selection.
Here is the initial code snippet for creating a basic menu bar:
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-type:none;
margin:0;
padding:0;
overflow:hidden;
}
li {
float:left;
}
a {
display:block;
width:60px;
background-color:#dddddd;
}
</style>
</head>
<body>
<ul>
<li><a href="#home">Menu1</a></li>
<li><a href="#news">Menu2</a></li>
<li><a href="#contact">Menu3</a></li>
<li><a href="#about">Menu4</a></li>
</ul>
</body>
</html>
A failed attempt at creating a dropdown menu by adding more elements to the original menu:
<!DOCTYPE html>
<html>
<head>
<style>
ul{
list-style-type:none;
margin:0;
padding:0;
overflow:hidden;
}
li{
float:left;
}
a{
display:block;
width:60px;
background-color:#dddddd;
}
</style>
</head>
<body>
<ul>
<li><a href="#home">Menu1</a> <-- not working
<ul>
<li><a href="#home">Menu1</a></li>
<li><a href="#news">Menu2</a></li>
<li><a href="#contact">Menu3</a></li>
<li><a href="#about">Menu4</a></li>
</ul>
</li>
<li><a href="#news">Menu2</a></li>
<li><a href="#contact">Menu3</a></li>
<li><a href="#about">Menu4</a></li>
</ul>
</body>
</html>
Functional code for a dropdown menu sourced from fiddle:
Providing this code reference for future developers seeking a working example of a dropdown menu implementation.
<ul>
<li class="mainmenu"><a href="#home">Menu1</a>
<ul class="submenu">
<li><a href="#home">Menu1</a></li>
<li><a href="#news">Menu2</a></li>
<li><a href="#contact">Menu3</a></li>
<li><a href="#about">Menu4</a></li>
</ul>
</li>
<li><a href="#news">Menu2</a></li>
<li><a href="#contact">Menu3</a></li>
<li><a href="#about">Menu4</a></li>
</ul>
CSS styling for the dropdown menu:
ul {
list-style-type:none;
margin:0;
padding:0;
overflow:hidden;
}
li {
float:left;
}
a {
display:block;
width:60px;
background-color:#dddddd;
}
li ul{
position:absolute;
display:none;
}
li:hover ul{
display:block;
}