Tailwind CSS is a utility based framework. Which is great in many ways. However, Tailwind CSS does not have a default set of components for you to get started with.
This is a series that will show you how to build various common UI components with Tailwind CSS
Today, we're going to be learning how to make a (good looking) button with Tailwind CSS.
Let's start by making a button
<button type="button">Button</button>
Let's add some padding and margins
<button type="button" class="m-2 px-8 py-2">Button</button>
Next, we can add text and background colors
<button type="button" class="m-2 px-8 py-2 bg-indigo-500 text-white">Button</button>
We should give our button rounded corners
<button type="button" class="m-2 px-8 py-2 bg-indigo-600 text-white rounded-lg ">Button</button>
Let's give our button a small shadow
<button type="button" class="m-2 px-8 py-2 bg-indigo-600 text-white rounded-lg shadow-sm">Button</button>
It is important that we add :hover
and :focus
styles to our button
<button type="button" class="m-2 px-8 py-2 bg-indigo-600 text-white rounded-lg shadow-sm hover:bg-indigo-500 focus:ring-2 focus:ring-indigo-200">Button</button>
Here's what our button should look like now 👇
Making 10 css classes 1
I think that a button with 10 classes is a bit .. too much.
Thank you so much @afif. This comment gave me inspiration to add this section to my article. There are too many classes on this button. However, thanks to the @apply
directive, we can make this one class. We can simply take all our classes and "apply" them to one class.
.btn {
@apply m-2 px-8 py-2 bg-indigo-600 text-white rounded-lg shadow-sm hover:bg-indigo-500 focus:ring-2 focus:ring-indigo-200;
}
Now, after rebuilding your css, you can replace all those classes with one class in your button.
<button type="button" class="btn">Button</button>
Thanks for reading and I hope you liked the article! 😊
Top comments (4)
I think that a button with 10 classes is a bit .. too much.
Thank you for this comment, really helpful.
We can use the
@apply
directive in Tailwind CSS to bring this down to one class.Creating an aesthetically pleasing button with Tailwind CSS involves combining utility classes for style and responsiveness. Begin by selecting background and text colors using 'bg-' and 'text-' classes, ensuring a visually appealing contrast. Add padding with 'px-' and 'py-' for a comfortable touch, and include rounded corners with 'rounded-' to soften the edges. Employ hover and focus states with 'hover:' and 'focus:' classes for interactive feedback. Experiment with shadow utilities like 'shadow-md' for a subtle lift. This thoughtful integration of Tailwind CSS classes enables the effortless crafting of visually appealing buttons tailored to your design preferences.
For more info, read here: purecode.ai/blogs/tailwind-button/
Tell me what you think! Comment here if you have any ideas to make my component look better or if you have any feedback in general of my post.