0
0
RailsHow-ToBeginner · 3 min read

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:install to 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:install
💻

Example

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:install after 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-rails gem 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:install
📊

Quick Reference

StepCommand or ActionDescription
1Add gem 'tailwindcss-rails' to GemfileInclude Tailwind integration gem
2bundle installInstall gems including Tailwind gem
3bin/rails tailwindcss:installGenerate Tailwind config and CSS files
4Use Tailwind classes in viewsWrite utility classes in HTML/ERB
5Restart Rails serverApply 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.