🔥
ExpressでTailwind CSS書き方教室
tailwindCSSのインストールと設定
昨今、流行っているtailwindCSSをExpressに組み込んでみます。他にもCDNやPostCSS等インストール方法がありますが、Expressと一番相性のいいインストール方法を紹介します。
powershell
md tailwindscss
cd tailwindscss
md src
md public
md views
powershell
npm init -y
npm install express tailwindcss pug express-handlebars
npx tailwindcss init
tailwind.config.jsができます。開きます。
pugをexpressで利用する場合はこんな感じにします。
tailwind.config.js
module.exports = {
content: ['./views/**/*.pug'],
theme: {
extend: {},
},
plugins: []
}
static(html)とhbs(Handlebars)をexpressで利用する場合はこんな感じ
tailwind.config.js
module.exports = {
content: ['./public/**/*.html','./views/**/*.hbs'],
theme: {
extend: {},
},
plugins: []
}
直接input.cssを使わないのでoutput.cssを作成しcssファイルを、pug,hbs,statics_htmlに読み込ませるようビルドします。baseクラス、componentsクラス、utilitiesクラスを、変換してcssにします。
src/input.css
@tailwind base;
@tailwind components;
@tailwind utilities;
確認するためのpublic/index.htmlを作成します。cssの出力パスを記載し確認用のtailwind用classを記載します。
public/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="css/tailwind.css" rel="stylesheet" />
</head>
<body>
<h1 class="text-3xl font-extrabold underline text-blue-900">Hello world!</h1>
</body>
</html>
powershell
npx tailwindcss ./src/input.css -o ./public/css/tailwind.css --watch
ビルドされたらpublic/index.htmlを確認します。underlineがひかれていればcssが通っています。
<h1 class="text-3xl font-bold underline">
Hello world!
</h1>
Tailwind CSS Container
コンテナーを中央に配置するときは、以下のように書きます。
<div class="container mx-auto bg-yellow-200">
<h1 class="text-3xl font-bold underline">
Hello world!
</h1>
</div>
<div class="container mx-auto">
<div class="columns-3">
<img src="https://loremflickr.com/520/240/random=1" />
<img src="https://loremflickr.com/520/240/random=2" />
<img src="https://loremflickr.com/520/240/random=3" />
</div>
</div>
Discussion