Simple Dropdown Navigation Menu with HTML, CSS & JavaScript
02/27/2021
Contents
Demo
Code
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Dropdown Menu</title>
<link rel="stylesheet" type="text/css" href="https://demo.plantpot.works/assets/css/normalize.css">
<link rel="stylesheet" href="https://use.typekit.net/opg3wle.css">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="container">
<div class="box" aria-haspopup="true">
<button id="btn-dropdown" class="btn-dropdown">Dropdown Menu</button>
<nav id="nav-dropdown" class="nav-dropdown">
<ul>
<li><a href="#">Menu 1</a></li>
<li><a href="#">Menu 2</a></li>
<li><a href="#">Menu 3</a></li>
</ul>
</nav>
</div>
</div>
</body>
</html>
CSS
@charset "utf-8";
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
font-size: 16px;
}
body {
background-color: #f7f4e5;
font-family: futura-pt, sans-serif;
-webkit-tap-highlight-color: rgba(0,0,0,0);
}
#container {
display: flex;
justify-content: center;
align-items: center;
position: relative;
width: 100%;
height: 100vh;
min-height: 300px;
padding: 20px 0;
}
.box {
position: relative;
}
.btn-dropdown {
padding: 10px 20px;
border: none;
border-radius: 4px;
background: #6666e2;
color: #fff;
font-size: 1.25rem;
outline: none;
cursor: pointer;
}
.btn-dropdown::after {
display: inline-block;
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
width: 8px;
height: 8px;
margin-left: 10px;
border-right: 2px solid #FFF;
border-bottom: 2px solid #FFF;
vertical-align: 4px;
content: '';
}
.btn-dropdown:hover {
opacity: .9;
}
.nav-dropdown {
display: none;
position: absolute;
top: 50px;
left: 0;
right: 0;
padding: 10px 0;
border-radius: 4px;
box-shadow: 0 0.5rem 2rem rgba(0, 0, 0, .1);
background-color: #fff;
}
.nav-dropdown ul {
list-style-type: none;
}
.nav-dropdown ul li {
padding: 8px 0;
font-size: 18px;
text-align: center;
cursor: pointer;
}
.nav-dropdown ul li a {
display: block;
color: #3d3935;
text-decoration: none;
}
.nav-dropdown ul li:hover {
background-color: #6666e2;
}
.nav-dropdown ul li:hover a {
color: #fff;
}
.nav-dropdown.is-open {
display: block;
}
.btn-dropdown.is-open::after {
-webkit-transform: rotate(-135deg);
transform: rotate(-135deg);
vertical-align: middle;
}
@media screen and (max-width: 480px) {
#container {
align-items: flex-start;
}
}
JavaScript
var btn = document.getElementById("btn-dropdown");
var nav = document.getElementById("nav-dropdown");
btn.addEventListener('click', () => {
if(!btn.classList.contains("is-open")) {
btn.classList.add("is-open");
nav.classList.add("is-open");
} else {
btn.classList.remove("is-open");
nav.classList.remove("is-open");
}
});