DEV Community

Cover image for Tailwind CSS under the hood

Tailwind CSS under the hood

Max Shen on February 10, 2024

Tailwind CSS defines itself on its official site as: A utility-first CSS framework packed with classes. In this post I'll explain to you what d...
Collapse
 
karsten_biedermann profile image
Karsten Biedermann

Thank you for your excellent article 👍. I stopped using it at some point due to the poor code readability. In reality, in large projects, it often looks like this:

<a class="rounded-md bg-indigo-600 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600"></a>

There's a good reason why solutions like this now exist, offering readable classes for use: daisyui.com

Collapse
 
seandinan profile image
Sean Dinan • Edited

I agree that it becomes a bit cluttered looking as a big long string, but I stopped inlining classnames in JSX a while back and it pretty much resolved the problem. My usual component structure is something like:

- /ControlsBar
  - index.jsx
  - utils.js
  - ControlsBar.stories.js
Enter fullscreen mode Exit fullscreen mode

so that the component file is something like:

import { classes } from './utils';

export default function ControlsBar({onSave, onCancel}){
  return (
   <div className={classes.wrapper}>
    <button className={classes.cancel} onClick={onCancel}>Cancel</button>
    <button className={classes.save} onClick={onSave}>Save</button>
  </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

and the utils file has:

export const classes = {
  wrapper: 'flex justify-between items-center border-t border-grey-3',
  cancel: 'text-grey-4 bg-grey-1 hover:bg-grey-2',
  save: 'text-blue-4 bg-blue-1 hover:bg-blue-2',
}

/* ...any utility functions for the particular component */
Enter fullscreen mode Exit fullscreen mode
Collapse
 
brense profile image
Rense Bakker

This is exactly what PandaCSS already does.

Thread Thread
 
seandinan profile image
Sean Dinan • Edited

I think it's a pretty common pattern. I made a package (tailwind-classlist) back in 2018ish that did something similar, although it's no longer maintained. Handled merging conflicting classes and everything as well.

Thread Thread
 
brense profile image
Rense Bakker

Nice!

Collapse
 
faiq157 profile image
Faiq Ahmad

NYC bro

Collapse
 
pengeszikra profile image
Peter Vivo

I like to use tw fare better than using any other CSS solution because the layout related solution so simple like grid gap-2 for vertical list. Also can solve dark/light skin change and responsive design at zero cost.

Collapse
 
brense profile image
Rense Bakker

Tailwind likes to pretend it's the only option with those benefits, but that's not really (really not) true. PandaCSS for example has the same benefits, but none of the downsides of having to learn a new utility class language.