Tailwind CSS has revolutionized the way we approach web design, offering a utility-first framework that allows for rapid development and easy customization. In this post, we’ll explore three lesser-known but incredibly useful Tailwind CSS tips that can help streamline your workflow and improve your code quality.
1. Use size-{n} for Equal Width and Height
Instead of separately specifying width and height, you can use the size-{n}
utility when you need an element to have equal dimensions.
<!-- Instead of this -->
<div class="w-12 h-12 bg-blue-500 rounded-full"></div>
<!-- Use this -->
<div class="size-12 bg-blue-500 rounded-full"></div>
This shorthand is handy for squares, circles, or any element where you want to ensure equal width and height.
2. Utilize divide-{y/x}-{n} for Consistent Spacing
When you need to add borders or dividers between child elements, instead of manually adding borders to each child, use the divide-{y/x}-{n}
utility on the parent. This approach ensures consistent spacing and reduces the amount of code you need to write.
<!-- Instead of this -->
<div>
<div class="py-4 border-b">Item 1</div>
<div class="py-4 border-b">Item 2</div>
<div class="py-4">Item 3</div>
</div>
<!-- Use this -->
<div class="divide-y">
<div class="py-4">Item 1</div>
<div class="py-4">Item 2</div>
<div class="py-4">Item 3</div>
</div>
This approach is mostly useful for lists, menus, or any layout where you need consistent separation between elements.
3. Apply Arbitrary Variants with [&_selector]:
Tailwind CSS allows you to apply styles to all matching child elements from the parent using the [&_selector]:
syntax. This technique keeps your HTML cleaner and more maintainable.
<!-- Instead of this -->
<ul>
<li class="mb-2 text-blue-500">Item 1</li>
<li class="mb-2 text-blue-500">Item 2</li>
<li class="mb-2 text-blue-500">Item 3</li>
</ul>
<!-- Use this -->
<ul class="[&_li]:mb-2 [&_li]:text-blue-500">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
This approach is particularly powerful for applying consistent styles to child elements without needing to modify each child individually.
You can write more efficient and maintainable code by using these useful Tailwind CSS tips. Remember, the key to mastering Tailwind is understanding its utilities and knowing when to use these powerful shorthands.
The official Tailwind CSS documentation has covered it all, you just need to find the jewels: https://tailwindcss.com/docs/installation
Stay tuned for more advanced Tailwind CSS tips in future posts!