Adding Tailwind CSS to Ruby on Rails 6 applications

Tailwind is a CSS framework that is quickly gaining popularity over other CSS frameworks. The reason for that, according to the creators of Tailwind:

Instead of opinionated predesigned components, Tailwind provides low-level utility classes that let you build completely custom designs without ever leaving your HTML.

Their perspective is that other frameworks try to do too much:

They come with all sorts of predesigned components like buttons, cards, and alerts that might help you move quickly at first, but cause more pain than they cure when it comes time to make your site stand out with a custom design.

This tutorial will demonstrate adding Tailwind CSS to Ruby on Rails. First, add Tailwind with yarn. From your project root:

1
yarn add tailwindcss

Then:

1
2
mkdir app/javascript/stylesheets
touch app/javascript/application.scss

In application.scss add the following lines:

1
2
3
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

Now in app/javascript/stylesheets/application.scss, add the following:

1
require("stylesheets/application.scss")

In your application.html.erbfile, add the following lines:

1
2
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

Make sure postcss.config.js looks something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
module.exports = {
  plugins: [
    require('postcss-import'),
    require('postcss-flexbugs-fixes'),
    require('postcss-preset-env')({
      autoprefixer: {
        flexbox: 'no-2009'
      },
      stage: 3
    }),
    require('tailwindcss'),
    require('autoprefixer')
  ]
}

Now create a landing controller with index method:

1
rails generate controller landing index

In app/views/landing/index.html.erb, put the following code that comes from their site:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<div class="max-w-sm rounded overflow-hidden shadow-lg mx-auto">
  <img class="w-full" src="/img/card-top.jpg" alt="Sunset in the mountains">
  <div class="px-6 py-4">
    <div class="font-bold text-xl mb-2">The Coldest Sunset</div>
    <p class="text-gray-700 text-base">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatibus quia, nulla! Maiores et perferendis eaque, exercitationem praesentium nihil.
    </p>
  </div>
  <div class="px-6 py-4">
    <span class="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2">#photography</span>
    <span class="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2">#travel</span>
    <span class="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700">#winter</span>
  </div>
</div>

In your routes.rb, add this:

1
root 'landing#index'

That’s it - you have successfully added Tailwind to your Rails project.