TailwindCss
1. 安装并且配置tailwindcss
# 删除原来安装的包
yan remove tailwindcss postcss autoprefixer
# 1.安装低版本包
yarn add tailwindcss@npm:@tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9
# 2.创建配置文件
npx tailwindcss init -p
# 3.创建css文件
/* ./src/tailwind.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer components {
.btn {
@apply px-4 py-2 bg-blue-600 text-white rounded;
}
}
# 4. 在main.js中引入创建的css文件
import "./taliwind.css"
2. 封装tailwindcss组件
大多数时候tailwindcss写样式会出现类名太长的问题,需要封装组件
将banner的类名封装成组件
<div class="banner">
<div class="order-1 sm:order-none w-11/12 sm:w-auto max-w-screen-sm inline-block text-white text-sm md:text-base mb-2 sm:mb-0">This is a section of some simple filler text, also known as placeholder text.</div>
<!-- close button - end -->
</div>
/*在引入的tailwindcss中将banner封装成组件*/
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer components {
.banner {
@apply flex flex-wrap sm:flex-nowrap sm:justify-center sm:items-center bg-indigo-500 relative sm:gap-3 px-4 sm:pr-8 ms:px-8 py-3;
}
}
3. base、components、utilities,variants分别是什么
3.1 base 清除所有标签的默认样式 也可以自定义样式
自定义标签样式
@layer base{
h1{
@apply text-blue-300
}
}
3.2 utilities 自定义工具类
/*将ul前面放一张图片*/
@layer utilities{
.list-img-@{
list-style-image: url("..");
/*//放一张图片*/
}
}
3.3 components 自定义组件
<div class="banner">
<div class="order-1 sm:order-none w-11/12 sm:w-auto max-w-screen-sm inline-block text-white text-sm md:text-base mb-2 sm:mb-0">This is a section of some simple filler text, also known as placeholder text.</div>
<!-- close button - end -->
</div>
/*在引入的tailwindcss中将banner封装成组件*/
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer components {
.banner {
@apply flex flex-wrap sm:flex-nowrap sm:justify-center sm:items-center bg-indigo-500 relative sm:gap-3 px-4 sm:pr-8 ms:px-8 py-3;
}
}
3.4 variants 生成多变体(就是哪些hover,鼠标移入移出啥的)
@layer components{
/*生成多从变体 就是哪些hove 鼠标移入啥的*/
@variants hover,focus{
.btn{
@apply px-4
}
}
}
4. 上线环境下减小打包体积
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [],
// 生产优化减小打包体积
purge: [
'./src/**/*.html',
'./src/**/*.vue',
'./src/**/*.jsx',
],
theme: {
// 自定义的适配多端
extend: {
screens: {
sm: '480px',
md: '768px',
lg: '976px',
xl: '1440px',
ms:'1000px'
},
},
},
plugins: [],
}
5. 注意事项
- /如果使用vite创建的vue3项目/ 生成的tailwindcss.config.js需修改成tailwindcss.config.cjs 生成的postcss.config.js 需修改成postcss.config.cjs
- 不建议使用vue add tailwindcss来安装tailwindcss