Feature blog image

Simple loading spinners with Tailwind

2 min read

We can create nice loading spinners without using external libraries and even without JavaScript. Here are two simple examples of how to create loading spinners with Tailwind CSS.

Simple div spinner

We can create a simple loading spinner with just a <div> and some Tailwind CSS classes.

Looks pretty good, right? Let's take a look at the code.


<div class="h-6 w-6 animate-spin rounded-full border-b-2 border-current" />

The classes explained:

Simple SVG spinner

Now, let's create a more complex spinner with SVG.

We will start with the SVG element.


<svg class="h-6 w-6 animate-spin" viewBox="0 0 100 100"></svg>

The SVG element has a viewBox of 100x100. This means that the SVG element will be 100x100 pixels. We will also use h-6 and w-6 classes to set the height and width of the SVG element, and the animate-spin class to animate the spinner.

Now, we will add a circle to the SVG element.


<circle
fill="none"
stroke-width="10"
class="stroke-current opacity-40"
cx="50"
cy="50"
r="40"
/>

Let's take a closer look at the used attributes:

Now, we will add a second circle to the SVG element.


<circle
fill="none"
stroke-width="10"
class="stroke-current"
stroke-dasharray="250"
stroke-dashoffset="210"
cx="50"
cy="50"
r="40"
/>

The second circle is almost the same as the first one, but it has two additional attributes:

This means that we will only see a part of the second circle. If you want to know more about the stroke-dasharray and stroke-dashoffset attributes, have a look at this article.

Here is the combined code:


<svg class="h-6 w-6 animate-spin" viewBox="0 0 100 100">
<circle
fill="none"
stroke-width="10"
class="stroke-current opacity-40"
cx="50"
cy="50"
r="40"
/>
<circle
fill="none"
stroke-width="10"
class="stroke-current"
stroke-dasharray="250"
stroke-dashoffset="210"
cx="50"
cy="50"
r="40"
/>
</svg>

Posted in: tailwind, spinner, loading