How to create a simple dropdown menu using JavaScript and CSS?
by velo_ninja
HTML
<div class="container">
<button id="web">Web</button>
<div id="menu" class="menu-items">
<a href="#html">HTML</a>
<a href="#css">CSS</a>
<a href="#js">JavaScript</a>
<a href="#php">PHP</a>
</div>
</div>
CSS
#web {
background-color: grey;
color: white;
padding: 10px;
border: none;
outline: none;
cursor: pointer;
min-width: 90px;
}
#web:hover,
#web:focus {
background-color: #4b79a1;
color: white;
}
.container {
position: relative;
}
.menu-items {
display: none;
position: absolute;
background-color: grey;
min-width: 90px;
text-align: center;
}
.menu-items a {
display: block;
background-color: grey;
color: white;
padding: 10px;
border: none;
outline: none;
cursor: pointer;
text-decoration: none;
margin-bottom: 2px;
}
.menu-items a:hover {
background-color: #4b79a1;
}
.show {
display: block;
}
JavaScript
document.getElementById("web").onclick = function() {
document.getElementById("menu").classList.toggle("show");
}