DEV Community

Cover image for Animated Hamburger Menu with Tailwindcss
Obaseki Noruwa
Obaseki Noruwa

Posted on

Animated Hamburger Menu with Tailwindcss

Most developer use svg hamburger menu icon when developing hamburger menu for their frontend web project, in this post i will show you how to build hamburger menu with animation in tailwindcss.

We are to create three horizontal line stacked vertically, to resemble an hamburger. Below is a graphical representation of the hamburger menu with animation.

Hamburger Menu Image

Create two div tags, one outer and the other inner div. we focus on the inner div tag by giving a width of 4rems w-16, height h-2, background-color bg-black and border-radius rounded-full.

Div Class

Div Width & Height

The next step will be to create the div pseudo-elements (&::before, &::after).

To create the div ::before pseudo-element, we write the following tailwindcss utility classes before:content-[‘’], before:absolute, before:w-16, before:h-2, before:bg-black, before:rounded-full, before:-translate-y-4.

Before Pseudo-Element

Before Pseudo-Element Image

For the ::after pseudo element, we copy the code from the ::before pseudo element above, but this time we remove the negative sign from the start of the translate-y-4 tailwindcss utility class: We replace before:-translate-y-4 with after:translate-y-4.

After Pseudo-Element Image

After Pseudo-Element Image

We add an id to our outer div to enable us have a mouseEvent (click) and have a reference to the outer div.

Outer div id

JavaScript Code

We add the following tailwindcss utility class to be applied to the hamburger-toggle class: [&>div]:h-0 [&>div]:bg-white [&>div::before]:before:translate-y-0 [&>div::before]:before:rotate-45 [&>div::before]:after:translate-y-0 [&>div::before]:after:-rotate-45

ToggleMenu Utility Class

Finally, we add some transition properties to the div and div pseudo-elements (&::before, &::after) for smooth animation, transition-all duration-150, before:transition-all before:duration-150, after:transition-all after:duration-150.

Full Code

Final Image

I hope this tutorial helped you understand how to create an hamburger menu with tailwindcss. If you do not understand the concept and the utility classes of tailwindcss, please visit tailwindcss website for better understanding and best practices when using the css framework.

Here is the link to the hamburger menu code on stackblitz: click me

Latest comments (2)

ramzifartas profile image

where did u put the style tag?!

noruwa profile image
Obaseki Noruwa • Edited

Edited: I placed it in the head tag, please visit the stackblitz link I provided below.