I’m creating a hamburger menu icon in Vue.js with TailwindCSS, where three lines transform into an ‘X’ when clicked. The expected behavior is:
Open Menu:
- Top line rotates 45 degrees and moves down slightly.
- Middle line fades out.
- Bottom line rotates -45 degrees and moves up.
Closed Menu:
- All lines form the hamburger icon again.
The issue is with the bottom line’s alignment. During the transition, the bottom line becomes misaligned and doesn’t properly align with the ‘X’ shape. I’ve used TailwindCSS utilities like translate and rotate but haven’t found a smooth solution.
Here’s my code:
<template>
<div class="md:hidden mr-6 mt-3">
<button @click="toggleMenu" class="text-gray-700 focus:outline-none">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" class="relative">
<path :class="menuOpen ? 'rotate-45 translate-x-1' : 'rotate-0'" d="M2 6C2 5.44772 2.44772 5 3 5H21C21.5523 5 22 5.44772 22 6C22 6.55228 21.5523 7 21 7H3C2.44772 7 2 6.55228 2 6Z" fill="currentColor"/>
<path :class="menuOpen ? 'opacity-0' : 'opacity-100'" d="M2 12.0322C2 11.4799 2.44772 11.0322 3 11.0322H21C21.5523 11.0322 22 11.4799 22 12.0322C22 12.5845 21.5523 13.0322 21 13.0322H3C2.44772 13.0322 2 12.5845 2 12.0322Z" fill="currentColor"/>
<path :class="menuOpen ? '-rotate-45 -translate-x-1' : 'rotate-0'" d="M3 17.0645C2.44772 17.0645 2 17.5122 2 18.0645C2 18.6167 2.44772 19.0645 3 19.0645H21C21.5523 19.0645 22 18.6167 22 18.0645C22 17.5122 21.5523 17.0645 21 17.0645H3Z" fill="currentColor"/>
</svg>
</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
const menuOpen = ref(false);
const toggleMenu = () => {
menuOpen.value = menuOpen.value;
}
</script>
Issue: The bottom line is misaligned when transitioning into the ‘X’. I’ve tried adjusting translate, but it doesn’t seem to fix the issue.
Any ideas on how to fix the alignment?
I tried changing the translate property but they don’t work as expected
2