5 Best Practices for Preventing Chaos in Tailwind CSS

Rate this content
Bookmark

Tailwind blew in sweeping developers into two opposing camps. You have already picked your side, you’re either team pro Tailwind or you run far away. But what if I told you there is a third option? 

This CSS framework should come into play only when the perfect type of project calls for gentle breezes. In this talk, with illustrative examples, we'll elaborate on how to improve the experience of working with Tailwind CSS using simple practices. I’ll challenge your preconceptions and answer the important question, for which cases Tailwind is the best solution or when it's better to choose an alternate CSS tool.

This talk has been presented at React Advanced 2024, check out the latest edition of this React Conference.

FAQ

One major drawback is the potential for very long class lists, which can clutter the project as it grows, especially if not used with a design system and component approach.

Tailwind CSS is popular for its convenience and ability to speed up the layout process by providing a ready-made list of classes, allowing developers to build projects quickly without worrying about naming CSS classes.

Best practices include using fewer utility classes, grouping and semantically naming design tokens, maintaining class order, minimizing build size, and using style variants.

You can maintain consistency by sorting classes according to their function and using tools like the official Prettier plugin for Tailwind CSS to automate class sorting.

No, Tailwind CSS is not a universal solution for all projects. It is important to use Tailwind wisely and consider it as one of many tools, choosing the right tool based on project requirements.

Semantic naming of design tokens is important because it makes the design system easier to understand and expand, helping to maintain consistency and readability as the project grows.

Monitoring the bundle size is crucial because larger web pages take longer to load, which can lead to loss of users. Minifying CSS and optimizing the build with tools like css-nano can help manage bundle size.

Using sets of style variants avoids issues when overriding classes, helps unify the application's appearance, and reduces the likelihood of visual regressions when changing styles.

To reduce the number of utility classes, use shorthand properties like vertical margins instead of individual top and bottom margins, omit default properties like flex-row, and use shorthand for RGBA format.

Tailwind CSS is most suitable for projects with a design system and a component approach, where design tokens and semantic organization of styles are used effectively.

Nina Torgunakova
Nina Torgunakova
10 min
28 Oct, 2024

Comments

Sign in or register to post your comment.
Video Summary and Transcription
Today we're going to talk about best practices for using Tailwind CSS. Tailwind CSS is a popular and controversial tool. It balloons within developers into two opposing camps. For some tasks, Tailwind is extremely cool. After working with Tailwind for a long time, I have identified two main requirements where Tailwind is suitable, and without them, it's better to choose an alternative tool. The first requirement is the project must have a design system. The second requirement for using Tailwind CSS is that your project must have a component approach. If you have a design system and a component approach, then Tailwind CSS may be a nice option for you. Instead of specifying the same margin at the top or the bottom, you can specify only a vertical one. Second rule while working with Tailwind is group design tokens and name them semantically. Rule number three, keep class ordering. The next advice for using Tailwind will be useful not only for Tailwind, but also when working with any content tools, monitor the bundle size and try to optimize it. The last rule for Tailwind, use sets of style variants to avoid problems when overriding classes. Instead of passing classes arbitrarily via props, define a set of variants for the component. Use fewer utility classes, group design tokens, and name them semantically. Keep class ordering, minimize your build size, and use sets of style variants. Remember that Tailwind CSS is a useful tool, but not the only solution for all projects.

1. Introduction to Tailwind CSS

Short description:

Today we're going to talk about best practices for using Tailwind CSS. Tailwind CSS is a popular and controversial tool. It balloons within developers into two opposing camps. For some tasks, Tailwind is extremely cool. After working with Tailwind for a long time, I have identified two main requirements where Tailwind is suitable, and without them, it's better to choose an alternative tool. The first requirement is the project must have a design system. The second requirement for using Tailwind CSS is that your project must have a component approach. If you have a design system and a component approach, then Tailwind CSS may be a nice option for you.

Hi everyone. Today we're going to talk about best practices for using Tailwind CSS. My name is Nina. I'm a front-end engineer at Devilmartian. We're engaged in product development for large companies and startups, and we also develop our own open-source products.

Tailwind CSS is a popular and controversial tool. It balloons within developers into two opposing camps. Tailwind has become so popular because many developers love it for its convenience and for speeding up the layout process. But at the same time, there are developers who can't stand it, especially because of really long Tailwind CSS class lists. But the truth is somewhere in the middle.

For some tasks, Tailwind is extremely cool. We don't need to think about the name of CSS classes. And with a ready-made list of classes, we can build a project extremely quickly. But on the other hand, Tailwind is not a silver bullet. There are cases when it will just pollute the project with a huge list of classes as it grows.

After working with Tailwind for a long time, I have identified two main requirements where Tailwind is suitable, and without them, it's better to choose an alternative tool. And the first requirement is the project must have a design system. Tailwind is closely connected with the philosophy of the design system in which we use design tokens. Design tokens are atomic values such as colors, sizes or margins that are used throughout the project. If we use magic constants for the design properties everywhere, there is a high possibility that you can break something if you need to change a property, like a certain color, in all the places in the project, because you will need to search for a specific class in all your Tailwind class lists and replace it with another value. But if we use the design tokens, it becomes much easier and safer, because if we decide to change some design property, like a certain color, we can apply it in just one place, and it will be changed everywhere.

And the second requirement for using Tailwind CSS is that your project must have a component approach. The approach with CSS classes that Tailwind uses leads to verbose HTML structures, since classes are applied directly to elements. And if we can't encapsulate code into separate components, then as a project grows, the markup will become extremely difficult to read and maintain.

Here's an example of how the component approach works with Tailwind. Instead of copying and pasting a button like this everywhere with a large list of classes, we encapsulate it in a separate component and call it in one line.

Now, the good news is if you have a design system and a component approach, then Tailwind CSS may be a nice option for you. But to make long-term work pleasant and painless, you have to use this tool wisely and follow some best practices. The first, in Tailwind a long list of classes are a harsh reality, but this disadvantage should be mitigated by trying to use only those Tailwind classes that are necessary. Here are some examples of how you can reduce the number of classes and get the same result.

Read also

2. Best Practices for Using Tailwind CSS

Short description:

Instead of specifying the same margin at the top or the bottom, you can specify only a vertical one. Second rule while working with Tailwind is group design tokens and name them semantically. Rule number three, keep class ordering. The next advice for using Tailwind will be useful not only for Tailwind, but also when working with any content tools, monitor the bundle size and try to optimize it. The last rule for Tailwind, use sets of style variants to avoid problems when overriding classes.

Instead of specifying the same margin at the top or the bottom, you can specify only a vertical one. Instead of specifying flex-row for a container with display value of flex, you can omit it with the same result, since flex-row is a default value of the flex-direction property. And in this example, we can remove border opacity 50 by adding a postfix with a slash in the number 50 for the border-black property. And this will be a shorthand for the RGBA format. So knowing these tweaks helps cut down the list of classes quite a bit while still preserving the same result.

So when working with Tailwind, if the list of classes has grown, ask yourself if you can somehow cut it down. Second rule while working with Tailwind is group design tokens and name them semantically. Group related tokens together in a config file, separating them into different sections, such as colors or distances. Structured config will be much easier to read as a number of tokens grows. Also, remember the importance of semantic naming and name your design tokens according to their purpose. For example, if the color is an error warning, don't name it just as bright red, name it semantically like error. Semantics like grouping make it easier to expand the entire design system as the project grows, so we should keep this in mind.

Rule number three, keep class ordering. Look at these two blocks. They have classes that are responsible for different aspects, display properties, box model properties, decorative properties and so on. But all these classes are specified chaotically and it's difficult to immediately say how these two blocks differ. But if we sort the classes, then this difference becomes more understandable and becomes easier to read such a list. It's better to automate the sorting work. I recommend using the official Pretier plugin for Tailwind CSS and it will automatically sort your classes.

The next advice for using Tailwind will be useful not only for Tailwind, but also when working with any content tools, monitor the bundle size and try to optimize it. Why do you need to monitor the bundle size? Because the average size of web pages is constantly growing and if 12 years ago it was like 800 kilobytes, then two years ago the average web page size was already more than 2,000 kilobytes. That's a big growth. And the larger the web page size, the longer it takes to load and the longer the load time, the greater the loss of users. Therefore, when using Tailwind, it's worth minifying the resulting CSS to optimize the build.

The last rule for Tailwind, use sets of style variants to avoid problems when overriding classes. Imagine that we have a button component on the page with a default white background. We are trying to override this class in such a way as to make the background black. But overriding the Tailwind class this way won't work and the button will remain white. Instead of passing classes arbitrarily via props, define a set of variants for the component.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Build a Design System with React and Tailwind CSS
React Summit 2022React Summit 2022
27 min
Build a Design System with React and Tailwind CSS
Top Content
This Talk discusses design systems and how to build one using React and Tailwind CSS. Tailwind CSS provides utility classes for building complex layouts without writing CSS rules. Custom colors can be added to the Tailwind CSS config file, and font styles and text sizes can be customized. The entire Tailwind CSS configuration can be customized to meet specific requirements. Base styles can be added to the config file itself using a plugin. Reusable components can be created with Tailwind CSS, allowing for easy customization of size and color.
Rethinking CSS - Introducing Stylex
React Finland 2021React Finland 2021
25 min
Rethinking CSS - Introducing Stylex
Top Content
CSS + superpowers - bloat. How Stylex creates a zero-cost abstraction that gives CSS superpowers.
If You Were a React Compiler
React Summit US 2024React Summit US 2024
26 min
If You Were a React Compiler
Top Content
In this talk, the speaker aims to build an accurate understanding of how the new React compiler works, focusing on minimizing re-renders and improving performance. They discuss the concept of memoization and how it can be used to optimize React applications by storing the results of function calls. The React compiler automates this process by analyzing code, checking dependencies, and transpiling JSX. The speaker emphasizes the importance of being aware of memory concerns when using memoization and explains how the React compiler detects changes in function closure values. They also mention the Fibre Tree, which drives the reconciliation process and helps optimize performance in React. Additionally, the speaker touches on JSX transpilation, compiler caching, and the generation of code. They encourage developers to understand the code generated by the compiler to optimize specific sections as needed.
How to achieve layout composition in React
React Summit 2022React Summit 2022
8 min
How to achieve layout composition in React
This talk discusses achieving layout composition in React using Bedrock Layout Primitives. By componentizing CSS layout, complex layouts can be achieved and reused across different components. The talk also covers the challenges of achieving complex layouts, such as card lineups, and provides solutions for maintaining alignment and responsiveness. The BedrockLayout primitive library simplifies web layouts and offers flexibility in composing layouts.
Type-safe Styling for React Component Packages: Vanilla Extract CSS
React Advanced 2023React Advanced 2023
19 min
Type-safe Styling for React Component Packages: Vanilla Extract CSS
Watch video: Type-safe Styling for React Component Packages: Vanilla Extract CSS
Today's Talk introduces Vanilla Extract CSS, a type-safe styling method for React applications. It combines the benefits of scoped styling, zero runtime overhead, and a great developer experience. Vanilla Extract generates a static CSS file at build time, resulting in better performance. It is framework agnostic and offers a powerful toolkit, including Sprinkles for utility classes and CSS utils for calculations. With type safety and the ability to define themes and variants, Vanilla Extract makes it easy to create efficient, scalable, and maintainable design system component packages.
Moving on From Runtime Css-In-Js at Scale
React Summit 2023React Summit 2023
29 min
Moving on From Runtime Css-In-Js at Scale
Watch video: Moving on From Runtime Css-In-Js at Scale
This Talk explores the evolution of styling architecture, dynamic theming with style components, and optimizing style updates. It discusses the challenges of CSS migration and the choice between JavaScript and CSS native tooling. The Talk also touches on CSS tools and libraries, including Tailwind CSS and CSS in JS major libraries like MUI. The importance of picking a stack based on team members' strengths and the use of namespacing CSS for conflict-free dependency trees are highlighted.