DEV Community

Cover image for Integrating Tailwind CSS with Your Rails App: A Step-by-Step Guide
Afaq Shahid Khan
Afaq Shahid Khan

Posted on

Integrating Tailwind CSS with Your Rails App: A Step-by-Step Guide

Introduction:

Tailwind CSS has gained popularity among developers for its utility-first approach and flexibility. Integrating Tailwind CSS with your Rails application can enhance your frontend development experience, allowing for rapid prototyping and customizable styling. In this article, we'll walk through the steps to integrate Tailwind CSS into your Rails app and unleash its power for building beautiful interfaces.

Step 1: Install Tailwind CSS

First, let's install Tailwind CSS using npm. Navigate to your Rails application directory and run the following command:

npm install tailwindcss
Enter fullscreen mode Exit fullscreen mode

Step 2: Configure Tailwind CSS

Next, we need to create a Tailwind CSS configuration file. Run the following command to generate the default configuration file:

npx tailwindcss init
Enter fullscreen mode Exit fullscreen mode

This will create a tailwind.config.js file in your project directory. You can customize this file to tweak Tailwind CSS settings according to your project requirements.

Step 3: Include Tailwind CSS in Your Stylesheets

Now, let's include Tailwind CSS in your Rails application. You can import Tailwind CSS into your stylesheet using @import directive. Create a new file app/assets/stylesheets/tailwind.css and add the following line:

@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

Step 4: Configure PostCSS

To process Tailwind CSS, we need to configure PostCSS. Install PostCSS and Autoprefixer using npm:

npm install postcss-loader autoprefixer
Enter fullscreen mode Exit fullscreen mode

Next, create a PostCSS configuration file postcss.config.js in your project root directory and add the following content:

module.exports = {
  plugins: [
    require('tailwindcss'),
    require('autoprefixer'),
  ]
}
Enter fullscreen mode Exit fullscreen mode

Step 5: Update Webpacker Configuration

We need to update Webpacker configuration to process PostCSS. Open config/webpacker.yml and add postcss to the extensions list:

extensions:
  - .js
  - .css
  - .scss
  - .sass
  - .module.css
  - .module.scss
  - .module.sass
  - .pcss # Add this line
Enter fullscreen mode Exit fullscreen mode

Step 6: Use Tailwind CSS Classes in Your Views
Now that Tailwind CSS is integrated into your Rails app, you can start using its utility classes in your views. For example:

<div class="bg-blue-500 text-white p-4">
  Welcome to My Rails App with Tailwind CSS!
</div>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)