前言
最近尝试了下tailwind css,感觉效果不错,之后考虑在项目中推广,因此做个笔记记录下常见用法
一、安装与配置
- 由于项目中使用了postcss,因此采用如下安装方式
npm install -D tailwindcss postcss autoprefixer
- 创建 tailwind.config.js
module.exports = {
// 用于生产环境优化,自动移除未使用的CSS类,扫描src目录下所有html、js、vue文件中使用的类名
purge: ['./src/**/*.{html,js,vue}'],
// 为所有Tailwind生成的样式添加!important标记,确保Tailwind样式优先级高于其他CSS
important: true,
// 是否深色模式
darkMode: false,
// 主题扩展,自定义css写在此处
theme: {
extend: {}
}
}
- 创建 index.css
// 将此css引入到main.js中
@tailwind base;
@tailwind components;
@tailwind utilities;
- 修改 postcss.config.js
module.exports = {
plugins: [
// 增加以下两项
['tailwindcss', {}],
['autoprefixer', {}]
]
};
- VS Code 安装 Tailwind CSS IntelliSense
二、常见用法
1. 变量合并
var clx = 'flex items-center text-gray-700 bg-white px-8 py-5 transition hover:bg-amber-100'
<div className={clx}></div>
<div className={clx}></div>
<div className={clx}></div>
2. 样式复用
export const center = 'flex items-center justify-center'
export const card = 'border rounded-md p-4'
... ...
import { card } from 'componentCss'
<div className={card}></div>
3. 使用@apply构建class
.btn {
@apply rounded-md border border-solid border-transparent py-2 px-4
text-sm font-medium bg-gray-100 cursor-pointer transition
}
4. 自定义属性
export default function Button(props) {
const {className, primary, danger, sm, lg, success, ...other} = props
const base = 'rounded-xl border border-transparent font-medium cursor-pointer transition'
// type
const normal = 'bg-gray-100 hover:bg-gray-200'
const _p = primary ? 'bg-blue-500 text-white hover:bg-blue-600' : ''
const _d = danger ? 'bg-red-500 text-white hover:bg-red-600' : ''
const _s = success ? 'bg-green-500 text-white hover:bg-green-600' : ''
// size
const md = 'text-sm py-2 px-4'
const _sm = sm ? 'text-xs py-1.5 px-3' : ''
const _lg = lg ? 'text-lg py-2 px-6' : ''
const cls = classnames(base, normal, md, _p, _d, _s, _sm, _lg)
return (<button className={cls} {...other}>{props.children}</button>)
}
<Button>Normal</Button>
<Button danger sm>Danger</Button>
<Button primary>Primary</Button>
<Button success>Success</Button>
5. tailwind.config中extend扩展写法示例
extend: {
width: {
modal: '500px',// 弹窗高度
container: '1200px'// 布局宽度
},
height: {
list: '600px',
},
minHeight: {
// 列表最小高度
list: '580px'
},
fontSize: {
'font-base': '16px',
'font-base-sm': '14px',
'font-base-lg': '18px',
'font-base-xl': '20px',
'font-base-2xl': '22px',
'font-base-3xl': '24px'
},
colors: {
// 主色调
primary: {
DEFAULT: 'var(--bg-primary)',
},
// 文字颜色
text: {
primary: 'var(--text-primary)',
},
// 背景色
bg: {
primary: 'var(--bg-primary)',
}
},
backgroundColor: (theme) => theme('colors.bg'),
textColor: (theme) => theme('colors.text'),
borderColor: (theme) => theme('colors.primary')
}
使用时
<div class="bg-primary"></div>
总结
经过项目实战,总结了几个优势:
- 规范代码,便于维护与统一
- 能够避免多人协作时样式重复与样式覆盖,减少冗余代码量
- 减少代码行数,提升性能
- 微服务架构时可以避免各子系统加载样式时互相覆盖
- 后续人员维护时可更直观的看到每个dom的样式,不用去style文件中挨个层级搜索
- 维护时不需要考虑样式命名
7211

被折叠的 条评论
为什么被折叠?



