so I'm having a weird issue with Tailwind and it's transitions. I have a parent div with a background color that changes depending on the activeState. This has a transition and it works just fine.
Within that div I have a "dot" that toggles between being on the left and the right, depending on it's activeState. The transition on this does not work.
I'm not sure why the second div's transition isn't working. I've tried changing the code to be an absolute div with left-1 right-1 being what it toggles between but that also didn't work.
<div
className={`flex items-center ${
activeState ? "bg-red-400 " : "bg-gray-600 "
} w-11 h-6 rounded-full transition-all px-[2px]`}
>
<div
className={`bg-white w-5 h-5 rounded-full ${
activeState ? "ml-auto" : "mr-auto"
} transition-all`}
></div>
</div>
Instead of using margins, you may easily use translate
to move the slider either to 0
or 100%
of the full width.
const toggle = document.getElementById('toggle');
const dot = document.getElementById('dot');
let isActive = false;
toggle.addEventListener('click', () => {
isActive = !isActive;
toggle.classList.toggle('bg-red-400', isActive);
toggle.classList.toggle('bg-gray-600', !isActive);
if (isActive) {
dot.style.transform = 'translateX(100%)';
} else {
dot.style.transform = 'translateX(0)';
}
});
<script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
<div id="toggle" class="relative w-11 h-6 rounded-full bg-gray-600 transition-colors cursor-pointer">
<div id="dot" class="absolute top-[2px] left-[2px] w-5 h-5 bg-white rounded-full transition-transform duration-300">
</div>
</div>