Tailwind CSS 是一个功能强大实用优先的 CSS 原子性的库,可以帮助你快速构建现代化的用户界面。
它支持的种类框架也非常的多! 例如:
Vite
、Next.js
等...这个库给我们带来的好处就是可以给我们衍生出其他增强的体验!
比如说
shadcn/ui
、daisyUI
无样式 UI 库!这些 UI 库就是基于Tailwind CSS
适配开发的!参考: tailwindcss 官网
以下是安装和使用 Tailwind CSS 的步骤:
1.创建一个 React 项目
bash
npm create vite@latest my-project -- --template react
cd my-project
2.安装 Tailwind CSS
2.1 首先,你需要在项目中安装 tailwindcss
及其对等依赖 !
bash
// 1.安装 Tailwind CSS
npm install -D tailwindcss@3.4.17
// 2.安装对等依赖
npm install -D postcss autoprefixer
ps: 安装时我们要指定版本安装 与官网文档版本保持一致即可! 如果不指定版本、默认安装是就是
v4
版本的tailwindcss
。当你继续执行
npx tailwindcss init
就会报错, 没有可执行文件的信息!
bashPS D:\lx\project\emoji-picker> npx tailwindcss init npm ERR! could not determine executable to run npm ERR! A complete log of this run can be found in: C:\Users\AppData\Local\npm-cache\_logs\2025-03-08T04_37_23_510Z-debug-0.log
解决方式: 我们安装切换官网的版本下载安装即可解决。
bashnpm install -D tailwindcss@3.4.17
3. 初始化 Tailwind CSS 配置文件
3.1 安装完成后,你可以通过以下命令生成 tailwind.config.js
和postcss.config.js
配置文件:
因为要分析我们的代码, 把
Tailwind CSS
的代码指令, 编译成浏览器可以识别的 CSS。
bash
npx tailwindcss init -p
3.2 将这些路径添加到 tailwind.config.js
文件中的所有模板文件中。
tailwind.config.js 文件允许你自定义 Tailwind 的默认配置,例如颜色、字体、间距等。
js
/** @type {import('tailwindcss').Config} */
export default {
// 指定项目目录下那些文件需要处理!
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {},
},
plugins: [],
}
4. 创建 Tailwind CSS 入口文件
在你的项目中入口 CSS 文中引入 Tailwind 的基础样式、组件和工具类:
例如: src/index.css
css
@tailwind base;
@tailwind components;
@tailwind utilities;
ps: 且必须在你的项目入口 main.js 文件中将
index.css
文件引入到全局。
5. 在你的页面代码中使用 Tailwind CSS
tsx
function App() {
const [count, setCount] = useState(0)
return (
<>
<button className='text-pink-400 px-2 py-2 bg-slate-600 rounded'> Hello World </button>
</>
)
}
export default App
6. Vs Code
中Tailwind CSS
扩展插件
直接在 扩展商店直接安装下载即可。 它可以触发 Tailwind CSS 提示片段。
bash
Tailwind CSS IntelliSense
7.总结
- 一个好的扩展包,一个好的框架也好 ! 往往是因为它的产生,而影响起来的生态!让咱们可以加快开发速度!
- 如果你有更多问题,欢迎随时问我!😊