Utility first CSS is very powerful and flexible but it has one downside that I personally don't like - long long
long class attributes:
div(class="bg-gray-900 flex flex-col gap-24 absolute top-1/2 left-1/2 transform -translat-x-1/2 -translat-y-1/2 text-center")
and this one is not the longest one, but it's enough to understand that it's not so good.
The problem with this approach is that it's hard to read the code especially when there are so many complex elements.
It's possible to solve this problem with mixins and use one or several classNames but this can make your css file
very big and it will be hard to optimize it in the future.
Or you can use wrap elements with additional ones to distribute class names but this will bloat html with
There is another way how to solve this problem put your class name to variables for example something like i18n does.
But I would like to share less complex method using simple variables this can work in almost any modern framework or
almost any template language. In this short article I will use pug for demonstration.
So instead of writing all class names into class attribute you can use variable in pug:
- var myComponent = "bg-gray-900 flex flex-col gap-24 absolute top-1/2 left-1/2 transform -translat-x-1/2 -translat-y-1/2 text-center" div(class=myComponent)
But wait a minute what if I need some kind of modifier? Well there is also solution for that. You can split your
variables into different kind of levels so you could mix them too:
- var myComponentBase=" bg-gray-900 flex flex-col gap-24 absolute top-1/2 left-1/2 transform -translat-x-1/2 -translat-y-1/2 text-center " - var myComponentText1=" font-24 leading-32 font-800 " - var myComponentText2=" font-18 leading-32 font-400 " div(class=myComponentBase + myComponentText1) div(class=myComponentBase + myComponentText2) // or div(class=myComponentBase + " font-18 leading-32 font-400")
Variables can be global, you can put them into separate file include them where ever you need them. You can also
have separate file per component. As you can see there are a lot of possibilities with this approach everything
depends on your imagination!
There is one thing to keep in mind. Each approach has it's own downsides. The problem with this one is that if you
would like to debug something in a browser than to search for something in the code that it will be a little bit
tricky to dao that if your code is not organized well for example if your class name variables are somewhere far
away from your components that it will take more time to find them.
As for frameworks everything works very similar you put all your class names into variables and then use them where ever you want to use them. Additionally you can implement something like i18n but for utility first css.
In the end of the day you should decide which approach would you like to use, which downsides are acceptable for you!