<nav role="primary navigation">
<a href="#">Home</a>
<div class="dropdown">
<a href="#" class="dropdown-action">Services
<svg class="dropdown-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><title>chevron-down</title><g fill="none"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M15.25 10.75L12 14.25l-3.25-3.5"></path></g></svg></a>
<ul class="dropdown-menu">
<li><a href="#">SEO</a></li>
<li><a href="#">Content Strategy</a></li>
<li><a href="#">Copywriting</a></li>
<li><a href="#">Storytelling</a></li>
</ul>
</div>
<a href="#">About</a>
<a href="#">Contact</a>
<div class="dropdown">
<a href="#" class="dropdown-action">
Account
<svg class="dropdown-icon" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><title>chevron-down</title><g fill="none"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M15.25 10.75L12 14.25l-3.25-3.5"></path></g></svg>
</a>
<ul class="dropdown-menu">
<li><a href="#">Login</a></li>
<li><a href="#">Sign up</a></li>
</ul>
</div>
</nav>
nav {
width: 1020px;
display: flex;
align-items: center;
margin: 20px auto;
padding-bottom: 10px;
border-bottom: 1px solid #ddd;
}
nav a {
padding: 10px 16px;
border-radius: 4px;
display: inline-block;
color: #334155;
text-decoration: none;
}
nav a:hover {
color: #0ea5e9;
background-color: #f0f9ff;
}
.dropdown {
position: relative;
}
.dropdown-action {
display: flex;
align-items: center;
padding-right: 10px;
}
.dropdown-menu {
display: none;
list-style: none;
margin: 0;
padding: 10px 0;
border: 1px solid #cbd5e1;
border-radius: 6px;
box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1);
position: absolute;
top: 40px;
left: 5px;
min-width: 180px;
background: white;
}
.dropdown-menu.active {
display: block;
}
.dropdown-menu a {
display: block;
}
.dropdown-icon {
stroke: currentColor;
pointer-events: none;
}
View Compiled
class Dropdown {
constructor() {
this.dropdowns = document.querySelectorAll('.dropdown .dropdown-menu')
if (this.dropdowns.length) {
this.initialize();
}
}
initialize() {
document.addEventListener('click', (e) => {
if (e.target.classList.contains('dropdown-action')) {
this.hideOtherDropdowns(e.target);
this.handleClick(e.target);
} else {
this.hideOtherDropdowns(null);
}
});
}
handleClick(dropdownAction) {
this.dropdowns.forEach(dropdown => {
if (dropdown.parentElement.contains(dropdownAction)) {
dropdown.classList.add('active');
} else {
dropdown.classList.remove('active');
}
})
}
hideOtherDropdowns(dropdownAction) {
this.dropdowns.forEach((dropdown) => {
if (!dropdown.parentElement.contains(dropdownAction)) {
dropdown.classList.remove('active');
}
});
}
}
document.addEventListener('DOMContentLoaded', () => new Dropdown);
View Compiled
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.