How to Use Tailwind CSS with Ruby on Rails
To use
Tailwind CSS with Ruby on Rails, add the tailwindcss-rails gem and run its installer to set up Tailwind automatically. This configures Tailwind with Rails' asset pipeline, enabling you to write utility-first CSS in your views and components.Syntax
Use the tailwindcss-rails gem to integrate Tailwind CSS into your Rails app. The main commands are:
gem 'tailwindcss-rails'in your Gemfile to add the gem.bin/rails tailwindcss:installto install Tailwind and generate config files.- Use Tailwind utility classes directly in your HTML and view templates.
ruby
gem 'tailwindcss-rails'
# Then run in terminal:
bin/rails tailwindcss:installExample
This example shows how to add Tailwind CSS to a new Rails app and use a Tailwind class in a view.
ruby + erb
# In Gemfile ruby '3.1.0' gem 'rails', '~> 7.0.0' gem 'tailwindcss-rails' # Then run in terminal: bundle install bin/rails tailwindcss:install # In app/views/home/index.html.erb <h1 class="text-4xl font-bold text-blue-600">Welcome to Tailwind with Rails!</h1>
Output
A webpage showing a large, bold, blue heading that says: "Welcome to Tailwind with Rails!"
Common Pitfalls
Common mistakes when using Tailwind with Rails include:
- Not running
bin/rails tailwindcss:installafter adding the gem, so Tailwind is not set up. - Forgetting to restart the Rails server after installation.
- Using old asset pipeline methods instead of the new
tailwindcss-railsgem setup. - Not including the Tailwind directives (
@tailwind base;,@tailwind components;,@tailwind utilities;) in your CSS file.
ruby
# Wrong: Missing Tailwind install
# Gemfile only:
gem 'tailwindcss-rails'
# No install command run, so no Tailwind files generated
# Right:
bundle install
bin/rails tailwindcss:installQuick Reference
| Step | Command or Action | Description |
|---|---|---|
| 1 | Add gem 'tailwindcss-rails' to Gemfile | Include Tailwind integration gem |
| 2 | bundle install | Install gems including Tailwind gem |
| 3 | bin/rails tailwindcss:install | Generate Tailwind config and CSS files |
| 4 | Use Tailwind classes in views | Write utility classes in HTML/ERB |
| 5 | Restart Rails server | Apply changes and serve CSS correctly |
Key Takeaways
Add the tailwindcss-rails gem and run its install command to set up Tailwind in Rails.
Use Tailwind utility classes directly in your Rails views and components.
Always restart your Rails server after installing Tailwind to load changes.
Ensure Tailwind directives are present in your CSS for styles to apply.
Avoid legacy asset pipeline setups; use the tailwindcss-rails gem for modern integration.