8
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

RailsでTailwind CSSを使用する

はじめに

Rails に Tailwind CSS を導入する方法です。

環境

  • rails : 6.0.3.1
  • webpakcer : 4.2.2
  • tailwindcss : 1.4.6

Tailwind CSS のインストール

Terminal
$ yarn add tailwindcss

tailwind.config.js の作成

Terminal
$ yarn tailwindcss init

Tailwind CSS を読み込む CSS ファイルを作成

app/javascript/css/tailwindcss.css
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
app/javascript/packs/application.js
// 追加
import '../css/tailwindcss.css';

postcss.config.js の修正

postcss.config.js
module.exports = {
  plugins: [
    // ...
    // 追加
    require('tailwindcss'),
    require('autoprefixer'),
    // ...
  ]
}

動作確認

Terminal
$ bin/rails g controller home show
config/routes.rb
Rails.application.routes.draw do
  root 'home#show'
end
app/views/home/show.html.erb
<!-- 公式のサンプル -->
<!-- https://tailwindcss.com/docs/utility-first#overview -->

<div class="max-w-sm mx-auto bg-white shadow-lg rounded-lg overflow-hidden">
  <div class="sm:flex sm:items-center px-6 py-4">
    <img class="block mx-auto sm:mx-0 sm:flex-shrink-0 h-16 sm:h-24 rounded-full" src="https://randomuser.me/api/portraits/women/17.jpg" alt="Woman's Face">
    <div class="mt-4 sm:mt-0 sm:ml-4 text-center sm:text-left">
      <p class="text-xl leading-tight">Erin Lindford</p>
      <p class="text-sm leading-tight text-gray-600">Customer Support Specialist</p>
      <div class="mt-4">
        <button class="text-purple-500 hover:text-white hover:bg-purple-500 border border-purple-500 text-xs font-semibold rounded-full px-4 py-1 leading-normal">Message</button>
      </div>
    </div>
  </div>
</div>

http://localhost:3000/ にアクセス

下記のようにスタイルが適用されています。

TailwindCSS適用.png

参考文献

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
8
Help us understand the problem. What are the problem?