最近学习 tailwind css ,刚开始学习过程中先弄明白了这个 css 框架的使用方法就开始上手例子,首先第一个例子是使用cdn方式引入写的一个小按钮例子,用于熟悉一下基本写法。第二个例子就是使用create-react-app创建的项目写的响应式QQ音乐界面。在搭建环境中遇到一些问题记录一下。
按钮
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<title>Tailwind Css Demo1</title>
</head>
<body>
<button class="ml-32 mt-32 border-none text-lg text-white bg-purple-300 px-8
py-3 rounded-full cursor-pointer transition-all duration-200
hover:bg-purple-400 transform hover:scale-125 active:bg-green-500">
按钮
</button>
<button class="btn">
按钮
</button>
</body>
</html>
.btn {
margin-left: 128px;
margin-top: 128px;
border: none;
font-size: 18px;
color: white;
background-color: rgba(196,181,253);
padding: 12px 32px;
border-radius: 24px 24px;
cursor: pointer;
transition: all 200ms;
}
.btn:hover {
transform: scale(1.25);
background-color: rgba(167,139,250);
}
.btn:active {
background-color: rgba(11,152,35);
}
上面是两个一样的按钮,当然,active在这里无效,需要使用配置的方式,参考文档即可,从这里来看学习 tailwind css 并不难,刚开始使用不断对照文档就行了,等熟悉以后就可以飞快搭建自己的页面,无需在 css 和 html 之间来回切换,不过类名会很长也是它的一个缺点了。
Create React App 中使用
使用 create-react-app 脚手架创建的项目引入 tailwind css 实现QQ音乐界面,可基于配置去定制化实现效果,跟着官方文档来还是出现了一些问题的,下面将一步步介绍搭建过程。
- 首先第一步创建react项目,可参考 create-react-app
npx create-react-app my-app --template typescript
- 安装依赖( 选一种方式 )
npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
yarn add -D tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
- 安装依赖配置 tailwind css , 这里不介意使用官网的方式。使用 react-app-rewired 和 customize-cra 来自定义 webpack配置
- 修改 package.json
- 根目录新建 config-overrides.js, 名字别打错
const { override, addPostcssPlugins } = require('customize-cra')
module.exports = override(
addPostcssPlugins([
require('tailwindcss'),
require('autoprefixer')
])
)
- 创建 tailwind css 配置文件
npx tailwindcss-cli@latest init
module.exports = {
purge: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'],
darkMode: false, // or 'media' or 'class'
theme: {
colors: {
green: {
700: '#ccc'
}
},
extend: {}
},
variants: {
extend: {
backgroundColor: ['active']
}
},
plugins: []
}
colors 是我测试配置的一个,使用代码和效果图如下
const App = () => {
return (
<div className="bg-green-700">
home
</div>
)
}
可以看到确实生效了。补充一下,需要在 index.css 中引入样式文件,这些参考 文档 即可
5. 经过以上步骤就算搭建好了可以使用 tailwind css 的项目。接下来的步骤就是根据自己需求进行配置然后开发。
提示
以上使用的是tailwind2版本的,如果想按照官网步骤成功,可以改下面一步,如果希望 webstrom 有 tailwind 提示,需要将版本改成 2.1.4
yarn add -D tailwindcss@npm:@tailwindcss/postcss7-compat@2.1.4 postcss@^7 autoprefixer@^9