This tutorial aims to guide you through the best practices when writing Tailwind CSS. We will delve into how to maintain clean code, improve efficiency and enhance maintainability using Tailwind's utility-first approach.
By the end of this tutorial, you should be able to:
Basic knowledge of HTML and CSS would be beneficial.
Tailwind CSS is a utility-first CSS framework. Instead of pre-designed components, it provides low-level utility classes that let you build completely custom designs. Let's dive into the best practices.
In Tailwind, it's best to keep your CSS functional. Try to use utility classes directly in your HTML markup rather than creating custom classes.
<!-- Good -->
<div class="text-center bg-green-500 p-4">Hello, world!</div>
<!-- Bad -->
<div class="custom-class">Hello, world!</div>
In the above examples, you can see that the first one uses utility classes directly, making it easy to understand what styles are applied by just looking at the HTML.
@apply
Directive SparinglyWhile the @apply
directive can be helpful in some situations, overuse can lead to bloated CSS. It's best to use @apply
only when necessary.
/* Good */
.btn {
@apply px-4 py-2 bg-blue-500 text-white;
}
/* Bad */
.custom-class {
@apply px-4 py-2 bg-blue-500 text-white;
}
In the above examples, we see that the @apply
directive is used sparingly in the first example, which is the preferred approach.
Let's look at some practical examples.
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
Button
</button>
In this snippet, we are creating a blue button with white text. The hover effect darkens the button. The font-bold
class makes the text bold, py-2 px-4
sets padding, and rounded
gives the button rounded corners.
<div class="container mx-auto flex flex-wrap p-5 flex-col md:flex-row items-center">
<!-- Content goes here -->
</div>
In this example, we are creating a responsive layout that changes from a column layout to a row layout on medium and larger screens. The p-5
class adds padding, while items-center
aligns items in the center.
In this tutorial, we have covered some best practices when writing Tailwind CSS. We've learned to use functional CSS, use the @apply
directive sparingly, and seen how to create buttons and responsive layouts using Tailwind CSS.
To continue your learning, consider exploring more about responsive design with Tailwind, customizing your design with Tailwind Config, and using Tailwind CSS with JavaScript frameworks like React and Vue.
Create a card with a picture at the top, title, description and a button at the bottom.
Create a responsive navigation bar that collapses into a hamburger menu on small screens.
Customize a design by overriding the Tailwind default classes in your Tailwind Config.
Each exercise builds on the previous one, increasing in complexity. The solutions can be found in the Tailwind CSS documentation, but try to solve them on your own first. Happy coding!