DEV Community

Patrick Zocli
Patrick Zocli

Posted on • Updated on

4 time saving tailwind tips… ⏱️

When we learn a tech, around 40% of the knowledge we acquire comes from study and the rest from practice.

Tailwind is no exception.

So here are 4 tips I've had the pleasure of discovering during my long hours of coding with tailwind

1 - Utility classes

Tailwind offers several utility classes, which are combinations of different CSS properties. Here are some, unfortunately, less well-known ones

Container (container)

This component can be used to set the maximum size of an element as a function of screen width.
In effect, it maps the minimum size of the current breakpoint to the maximum size of the component. Useful if you prefer to code for a fixed screen size.

Size (size-*)

Sets the height and width of an element at the same time: w-10 h-10 <=> size-10.

Line Clamp (line-clamp-*)

Reduces the number of lines in a text block by replacing the rest with "...".
line-clamp-3 sur un paragraphe
line-clamp-3 on a paragraph

Others

2 - Best approach

Tailwind is designed to be used with a mobile-first approach.
In other words, the class names (e.g. mb-4 text-lg) you add initially without the prefixes sm, md, lg ... are specifically intended for the mobile version.

tailwind mobile first responsive example

Then, if you prefer a completely different approach, you can always customize breakpoints.

3 - Common properties of children in the parent

I was surprised to discover that we could avoid duplicating the same style from one child to another by grouping common styles in the parent.
Let's say you have a simple list:

<ul class="flex gap-4">
  <li className="bg-black p-8"/>
  <li className="bg-black p-8"/>
  <li className="bg-black p-8"/>
</div>
Enter fullscreen mode Exit fullscreen mode

You can apply the same classname to all li children, adding them to those of parent ol but preceded by [&>*].

<ul class="flex gap-4 [&>*]:bg-black [&>*]:p-8">
  <li />
  <li />
  <li />
</div>
Enter fullscreen mode Exit fullscreen mode

[&>*] is a temporary selector which, as you may have guessed, transmits the class that follows it to all children.

4 - Prettier for better navigation

For all lovers of clean code, Tailwind recommends an organized way of ordering class names (details).
What's more, an extension is available to help with this. This plugin scans your templates for class attributes containing Tailwind CSS classes, and then sorts those classes automatically following their recommendation.

Image prettier tailwind


This is all I have to share with you for the time being. I hope I've introduced you to something new, and if you have any questions, I'd be happy to answer them !

Top comments (0)