LoginSignup
8
3

More than 3 years have passed since last update.

Tailwind CSSでトランジションとメディアクエリをサクッとPhoenixフレームワークに導入・実装する

Last updated at Posted at 2021-01-06

概要

Tailwind CSSで、CSSトランジションとレスポンシブ対応のためのメディアクエリを、WebフレームワークPhoenixに導入・実装します。

tailwind.gif

Tailwind CSS

flex, pt-4, text-center, rotate-90 などのCSSクラスを準備している「ユーティリティ・ファースト」のCSSフレームワークです。
モダンなWebサイトをすばやく構築できます。(公式より引用和訳)

Phoenix

膨大なアクセスやデータに対する高速処理、堅牢性に強みのあるプログラミング言語Elixir製のWebフレームワークです。

※ 本記事ではTailwindCSSをメイントピックにしているので、Phoenixについては以下の拙記事などご覧ください。

実行環境・バージョン

  • macOS
  • VSCode
  • Tailwind CSS 2.0.2
  • Node.js 14.15.4
  • Phoenix 1.5.7
    • Elixir 1.11.2 (compiled with Erlang/OTP 22)

コードとセットアップ

Phoenixプロジェクトディレクトリ作成

任意の名前でディレクトリをつくって、その中に入ってmix phx.newを実行します。

terminal
$ mix phx.new . --app sample_app --no-ecto

$ mix deps.get && mix deps.compile

$ cd assets && npm install && node node_modules/webpack/bin/webpack.js --mode development

TailwindCSSセットアップ

  • /assets内で、Tailwind CSSと依存パッケージをインストール。
terminal
$ npm install --save-dev tailwindcss@2.0.2 postcss@8.2.2 autoprefixer@10.1.0 postcss-loader@4.1.0
  • postcss.config.jsを新規作成しwebpack.config.jsにpostcss-loaderを追加。
assets/postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}
assets/webpack.config.js
use: [
  MiniCssExtractPlugin.loader,
  'css-loader',
  'postcss-loader',  // <-- add
  'sass-loader',
],
  • npxでtailwind.config.jsを生成。
terminal
$ npx tailwindcss init

   tailwindcss 2.0.2

   ✅ Created Tailwind config file: tailwind.config.js
  • 最後に、CSS(SCSS)にインポート。
assets/css/app.scss(以下コードを追加)
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

フロントページにお試し実装

公式トップのプロフィールカードや、こちらのチートシートを参考にして、お試し実装していきます。

lib/sample_app_web/templates/layout/app.html.eex
    <main role="main" class="container">
      <p class="alert alert-info" role="alert"><%= get_flash(@conn, :info) %></p>
      <p class="alert alert-danger" role="alert"><%= get_flash(@conn, :error) %></p>

      <!-- 追加ここから -->
      <section>
        <h1 class="text-center font-medium text-4xl">
          <%= gettext "team %{name}", name: "im" %>
        </h1>
      </section>
      <%= @inner_content %>
      <%= @inner_content %>
      <!-- 追加ここまで -->

      <%= @inner_content %>
    </main>
  </body>
  • 以下index.html.eexコード中にベタ書いているclassが、Tailwindの持つCSSクラスになります。
lib/sample_app_web/templates/page/index.html.eex(まるごと以下に書き換える)
<section class="my-8">
  <figure
    class="md:flex transition duration-500 ease-in-out bg-gray-100 hover:bg-indigo-200 transform hover:-translate-y-1 hover:scale-105 rounded-xl p-8 md:p-0"
  >
    <!-- プロフィール画像は`/assets/static/images/`に準備 -->
    <img
      class="w-32 h-32 md:w-56 md:h-56 rounded-full md:rounded-none mx-auto md:mx-0"
      alt="im image"
      src="<%= Routes.static_path(@conn, "/images/im.jpg") %>"
    >
    <div class="pt-6 md:p-8 text-center md:text-left space-y-4">
      <p class="text-xl font-semibold">
        "Aenean eleifend, massa id scelerisque lacinia, odio elit blandit diam, at varius nisi turpis ut neque. Nam at consequat erat."
      </p>
      <figcaption class="font-medium">
        <div>
          <p class="text-purple-600">im</p>
        </div>
        <div>
          <p class="text-gray-500">Web Developer</p>
        </div>
      </figcaption>
    </div>
  </figure>
</section>

test/sample_app_web/controllers/page_controller_test.exs(任意)
  test "GET /", %{conn: conn} do
    conn = get(conn, "/")
    assert html_response(conn, 200) =~ "Welcome to Phoenix!"  # <-- delete
    assert html_response(conn, 200) =~ "team im"    # <-- add
  end
end

ここまできたら、mix phx.serverでローカルサーバー起動して、お使いのWebブラウザでlocalhost:4000を確認してみましょう。

実装は以上になります。

補足(Tailwind CSS IntelliSense)

VSCodeのプラグインTailwind CSS IntelliSenseを導入すると、オートコンプリートやリンター機能のほか、Tailwind CSSクラスをホバーして生CSSを確認できたりするのでオススメです。
hover_css.png

おわりに

Tailwind CSSをPhoenixフレームワークにお試し導入しました。

BootstrapみたいにUIコンポーネントが用意されているものではないのですが(例えばbtn btn-primaryのように一発でUI部品を作れない)、カスタマイズ性に優れていてPhoenixとの親和性も良いと感じました。

また、Tailwind CSSを導入することによって以下の効果が得られそうな予感を持ちました。

  • CSSまわりのコードがスッキリする。(特にメディアクエリまわり)
  • クラス名が直感的であり、お手軽にねらった効果を実装できる。

普段使いにも良さそうです。


参考

8
3
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
3