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.
CSS
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
.
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
.
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
.
JavaScript
We add an id to our outer div to enable us have a mouseEvent (click) and have a reference to the outer div.
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
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
.
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
Top comments (9)
Hi, thanks for the great post! I found a issue at the tailwindcss utility class.
You wrote as below:
But, I think it should be like this.
Thanks for the correction 👍🏾
where did u put the style tag?!
Edited: I placed it in the head tag, please visit the stackblitz link I provided below.
The stackblitz does not seem to work. Only the middle div translate y to 0 works, not the 2 before/after rotates
looks like its the same issue as wataru pointed out :D
Thanks, now updated :D
Great, but how do you make it smaller or larger? I tried editing w-* and h-* all around the thing, and it still takes up the same space regardless of what you do.
Hi there!. if you are using tailwindcss CDN then it should work, try w-[10px] h-[4px].