In an effort to help reduce repetition and improve readability, Twind provides a domain specific grouping syntax that can be used in strings or template literals.
Let's see how we can use grouping to improve readability and save a few characters in the process.
On common complain of Tailwind (and utility classes) is long and unwieldy class names in markup:
These classes can be grouped using directive grouping:
focus variant classes can be grouped using variant grouping:
The background classes can be grouped using a combination of directive and variant (mixed) grouping:
As you can see, grouping saved a few characters. For some people, the grouped classes may improve readability. Other people may prefer the Tailwind style. Grouping is fully opt-in, highly expressive, and can be used as little or as much as you'd like.
TODO: playground using cx to expand groupings
The first grouping syntax works by factoring out common directive prefixes. Below is an example of a rule set without directive grouping and the equivalent rule set with
border factored out.
This reduced repetition in this rule set by about 20% but the output is still the same!
The second grouping syntax works by factoring out common variants. Both responsive and pseudo variants are supported in various combinations.
Note how rules within tagged template literals are able to span multiple lines
It is possible to nest directive groups inside of responsive groups and vice versa, however it is important to note that nesting responsive variants inside of responsive variants doesn't make sense and is not permitted.
Thanks to some ordering logic in the compiler, both of the above groupings will result in the same output. That is to say more generally, that directive groupings always get expanded before variant groupings.
Some directives like
ring need to be applied themselves as well as being a prefix. In this case you can use the reserved
& character which is replaced literally with the current prefix: