daniebker

How to: Tailwindcss animated progress bar

· [Daniel Baker]

As part of a project I’m working on I wanted to add an animated progress bar for some visual stimulation in the page. Since I’m using tailwindcss I was easily able to create a progress bar but I was struggling to get it to animate using the solutions I found on stackoverflow.

In the end I settled on adding a custom animate-progress class and attaching some keyframes to it starting the width from 0.

Here’s the code for a progress bar in tailwindcss. The {percent} here is a variable that you’d pass to your page.

<div class="w-full h-6 bg-gray-700 rounded-full dark:bg-gray-200">
  <div class="h-6 bg-green-600 rounded-full dark:bg-green-500 motion-safe:animate-progress" style="width: {percent}%"></div>
</div>

And an animate-progress class that keyframes width from 0 to a target %.

	@keyframes progress {
		from {
			width: 0;
		}
	}

	.animate-progress {
		display: block;
		animation: progress 1500ms ease-in 1;
	}

However, like this we’re not fully accessibility compliant since visitors to our site may suffer from too many animations. As a result we should respect accessibilty preferences of the user and reduce motion in the page. Tailwindcss also has modifiers for reducing motion for those users that specify it at the OS level. Adding motion-safe: before the animate-progress class should prevent the animation when users have that toggle enabled in their os. See the tailwindcss docs for more information.

You can also checkout the live version on CodePen.