I have just started really exploring Tailwind CSS and so far, love just how customizable things are. In contrast, with Bootstrap or any other framework, you would likely need to write several custom classes to get what you want. But even the default setup for Tailwind provides a plethora of options for you to customize away without writing any CSS, but rather just attaching classes in your HTML as needed.
I have seen a few different ways to get Tailwind into a Rails 6 project but this is the way I settled on and found easiest. I have included it to run via Webpacker rather than the asset pipeline. I have read in a few places that it's likely that future versions of Rails won't even include the asset pipeline, so besides the efficiency alone of Webpacker, it's probably a good reason to start using it completely now. So let's do this.
Add Tailwind to your project via Yarn
yarn add tailwindcss
Update Your PostCSS Config File
In the root of your project is a file called postcss.config.js. That will need to be updated like below. This tells Rails to require Tailwind CSS and where it is coming from, which we will set up after this to run via Webpacker.
Add Tailwind Components to work with Webpacker
Then make a file called application.scss inside the stylesheets folder. This can be done in the editor of your choice or as before, you could use Terminal like below.
Get the default Tailwind Config File into your project
This is where all the default styles/classes are defined in Tailwind. The easiest way to do this is through the terminal with node js. Be sure you are in the stylesheets folder as you were above.
That should create your tailwind.config.js file with all the base styles inside your stylesheets folder.
In the application.scss, you then need to import Tailwind.
require("@rails/ujs").start() require("turbolinks").start() require("@rails/activestorage").start() require("channels") import "stylesheets/application"; # Added this line where Tailwind CSS is
The last thing you will need to do is add a stylesheet_pack_tag to your layout file.
<%= stylesheet_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
Then you should have Tailwind working. Be sure to restart your server in development if needed to reinitialize Webpacker.
Optional: Add Custom Components
One thing I picked up while taking the Hello Rails master class (which I highly recommend), is that you will want to also make it possible to create your own custom components at some point too. So let's set that up as well.
Now you pull that component and its classes simply by importing to you application.scss file in the stylesheets folder like such:
Once again, I learned the bulk of doing it this way through the Hello Rails course. Check it out if you want to take your Rails and design game to the next level.