logo My Digital Garden

Animated Hamburger

By James Kolean on Jan 7, 2023
Demo: https://codepen.io/jameskolean/pen/GRBrZdK
Tailwind
banner

I ran across an animated hamburger menu in a Tailwind demo, I don’t recall where.

I created this codepen so I can reference it later.

Here is the Html

<button aria-label="Menu button" class="hamburger focus:outline-none" id="menu-btn">
    <span class="hamburger-top"></span>
    <span class="hamburger-middle"></span>
    <span class="hamburger-botton"></span>
</button>

<div id="mobile-menu" class="absolute hidden flex-col items-center self-end mt-2 py-8 space-y-6 font-bold left-6 right-6 bg-slate-800 drop-shadow.md">
    <a href="/">Home</a>
    <a href="/posts">Garden</a>
    <a href="/about-me">Me</a>
    <a href="/todo">Todo</a>
</div>

and the CSS

.hamburger {
    cursor: pointer;
    width: 24px;
    height: 24px;
    transition: all 0.25s;
    position: relative;
}

.hamburger-top,
.hamburger-middle,
.hamburger-botton {
    position: absolute;
    top: 0;
    left: 0;
    width: 24px;
    height: 2px;
    background: black;
    color: black;
    transition: all 0.25s;
    transform: rotate(0);
}

.hamburger-middle {
    transform: translateY(7px);
}

.hamburger-botton {
    transform: translateY(14px);
}

.open {
    transform: rotate(90deg);
    transform: translateY(0px);
}

.open .hamburger-top {
    transform: rotate(45deg) translateY(6px) translate(6px);
}

.open .hamburger-middle {
    display: none;
}

.open .hamburger-botton {
    transform: rotate(-45deg) translateY(6px) translate(-6px);
}

finally some javascript to make it do it’s thing

const menuBtn = document.getElementById("menu-btn");
const nav = document.getElementById("mobile-menu");
if (menuBtn && nav) {
    menuBtn.addEventListener("click", () => {
        menuBtn.classList.toggle("open");
        nav.classList.toggle("flex");
        nav.classList.toggle("hidden");
    });
}
© Copyright 2023 Digital Garden cultivated by James Kolean.