LoginSignup
1
1

More than 1 year has passed since last update.

Tailwind CSSの導入

Last updated at Posted at 2021-12-01

Tailwind CSSとは

CSSプロパティを予めラップしたクラスのユーティリティ集です。
これらをHTMLタグのclassnameに直接指定するので、cssファイルを使用する必要がなく、可読性が上がります。
また、BEMやOOCSS等の命名規則に縛られる必要もありません。
メリットは記述量の削減や可読性向上、ファイルサイズの縮小等があり、デメリットはクラスの記述が増加することと、それらのユーティリティクラスを使いこなすのが面倒である事です。

.css
div {
  display: flex;
  justify-content: center;
  font-size: 0.875rem;
  line-height: 1.25rem;
}
tailwindcss
<div className="flex justify-center text-sm">
  <p>Hello World</p>
</div>

チートシート

導入方法

以下の公式サイトからインストールを行います。

installationから使用しているフレームワークを選択すれば、各フレームワークのインストールから手順を確認できます。
ここではNext.js環境にてインストールを行います。

インストール

npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
npx tailwindcss init -p

Tailwindの設定

インストールが完了すると、プロジェクトフォルダ直下にtailwind.config.jsが作成されます。
今回は以下のように、purgeの設定のみ変更します。

module.exports = {
  purge: ["./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}"],
  darkMode: false, // or 'media' or 'class'
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
};

purgeはデプロイ時にクラスユーティリティを生成するファイルを決定します。
デフォルトでは全てが対象で膨大な量となるので、pagesとcomponents配下を指定します。

インポート

プロジェクトファイル内でTailwind CSSをインポートします。

_app.js
import "tailwindcss/tailwind.css";

続いて、プロジェクトのcssファイル内でtailwindをインクルードします。
cssファイルの名称はフレームワーク毎に異なります。
ここではNext.js環境なので、globals.cssに以下を記載します。

globals.css
@tailwind base;
@tailwind components;
@tailwind utilities;

これで基本的な環境設定は完了です。

VSCodeで入力補完

Tailwind CSSのユーティリティクラスを入力補完してくれる拡張機能をインストールします。
Marketplaceで「Tailwind CSS IntelliSense」をインストールします。
settings.jsonに以下の変更を加えます。

settings.json
{
  "editor.tabSize": 2,
  "workbench.tree.indent": 2,
  "editor.suggestSelection": "first",
  "vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue",
  "tailwindCSS.experimental.classRegex": [
  ],
  "editor.quickSuggestions": {
    "strings": true
  }
}

問題なく入力補完が効いていれば完了です。
スクリーンショット 2021-12-01 13.40.38.png

1
1
0

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
1
1