This snippet demonstrates a modern hamburger menu enriched with polished micro-interactions. When clicked, the classic three-line icon gracefully transforms into an “X”, delivering clear and intuitive visual feedback to the user.
This fluid animation is powered by a straightforward combination of HTML, CSS, and minimal JavaScript.
<!-- HTML -->
<button class="hamburger-menu" aria-label="Menu" aria-expanded="false">
<span class="line line-1"></span>
<span class="line line-2"></span>
<span class="line line-3"></span>
</button>/* CSS */
.hamburger-menu {
display: flex;
flex-direction: column;
justify-content: space-between;
width: 48px;
height: 32px;
background: transparent;
border: none;
cursor: pointer;
padding: 0;
position: relative;
transition: transform 0.3s ease;
}
.hamburger-menu:focus-visible {
outline: 2px solid #3b82f6;
outline-offset: 6px;
border-radius: 4px;
}
.hamburger-menu:hover {
transform: scale(1.05);
}
.hamburger-menu .line {
display: block;
width: 100%;
height: 4px;
background-color: #1e293b;
border-radius: 9999px;
transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
transform-origin: center;
}
/* Active (expanded) state styles */
.hamburger-menu.active .line-1 {
transform: translateY(14px) rotate(45deg);
background-color: #ef4444;
}
.hamburger-menu.active .line-2 {
opacity: 0;
transform: translateX(-20px);
}
.hamburger-menu.active .line-3 {
transform: translateY(-14px) rotate(-45deg);
background-color: #ef4444;
}// JavaScript
const hamburger = document.querySelector('.hamburger-menu');
hamburger.addEventListener('click', function() {
// Toggle active class
this.classList.toggle('active');
// Accessibility support (update aria-expanded)
const isExpanded = this.classList.contains('active');
this.setAttribute('aria-expanded', isExpanded);
}); cubic-bezier easing function to produce a natural, organic transition, avoiding stiff or mechanical movements.aria-label and aria-expanded are explicitly defined to communicate the menu’s toggled state to screen readers. Additionally, :focus-visible is employed to provide a distinct focus ring for keyboard navigation without compromising mouse-click aesthetics.transform and opacity), effectively preventing costly browser repaints and reflows for consistently smooth rendering at 60fps.