TailwindCSS 提供了强大的配置系统,允许开发者完全自定义设计系统,包括颜色、字体、间距、断点等各个方面。
配置文件基础
TailwindCSS 使用 tailwind.config.js 文件进行配置,该文件通常位于项目根目录。
基本配置结构
javascriptmodule.exports = { content: [ './src/**/*.{html,js,ts,jsx,tsx,vue,svelte}', ], theme: { extend: { // 自定义配置 }, }, plugins: [], }
颜色配置
1. 自定义颜色
javascriptmodule.exports = { theme: { extend: { colors: { 'brand': { '50': '#f0f9ff', '100': '#e0f2fe', '500': '#0ea5e9', '900': '#0c4a6e', }, 'accent': '#ff6b6b', }, }, }, }
2. 使用自定义颜色
html<div class="bg-brand-500 text-white"> 使用自定义品牌色 </div>
字体配置
1. 添加自定义字体
javascriptmodule.exports = { theme: { extend: { fontFamily: { 'sans': ['Inter', 'system-ui', 'sans-serif'], 'serif': ['Merriweather', 'Georgia', 'serif'], 'mono': ['Fira Code', 'monospace'], }, }, }, }
2. 字体大小配置
javascriptmodule.exports = { theme: { extend: { fontSize: { 'xxs': '0.625rem', 'huge': '5rem', }, }, }, }
间距配置
1. 自定义间距
javascriptmodule.exports = { theme: { extend: { spacing: { '128': '32rem', '144': '36rem', }, }, }, }
2. 使用自定义间距
html<div class="p-128 m-144"> 自定义间距 </div>
断点配置
1. 自定义断点
javascriptmodule.exports = { theme: { extend: { screens: { 'xs': '475px', '3xl': '1600px', 'print': {'raw': 'print'}, }, }, }, }
边框和圆角
1. 自定义边框
javascriptmodule.exports = { theme: { extend: { borderWidth: { '3': '3px', }, borderRadius: { '4xl': '2rem', }, }, }, }
阴影配置
javascriptmodule.exports = { theme: { extend: { boxShadow: { 'glow': '0 0 20px rgba(0, 0, 0, 0.5)', 'inner-lg': 'inset 0 2px 4px 0 rgba(0, 0, 0, 0.06)', }, }, }, }
动画配置
javascriptmodule.exports = { theme: { extend: { animation: { 'bounce-slow': 'bounce 3s infinite', 'spin-slow': 'spin 3s linear infinite', }, keyframes: { 'bounce-slow': { '0%, 100%': { transform: 'translateY(-25%)', animationTimingFunction: 'cubic-bezier(0.8, 0, 1, 1)' }, '50%': { transform: 'translateY(0)', animationTimingFunction: 'cubic-bezier(0, 0, 0.2, 1)' }, }, }, }, }, }
插件系统
1. 使用官方插件
javascriptconst forms = require('@tailwindcss/forms'); const typography = require('@tailwindcss/typography'); module.exports = { plugins: [ forms, typography, ], }
2. 创建自定义插件
javascriptconst plugin = require('tailwindcss/plugin'); module.exports = { plugins: [ plugin(function({ addUtilities, theme }) { const newUtilities = { '.text-shadow': { textShadow: theme('textShadow.DEFAULT'), }, }; addUtilities(newUtilities); }), ], }
预设配置
TailwindCSS 支持预设配置,可以在多个项目间共享配置:
javascript// tailwind.config.js module.exports = { presets: [ require('./tailwind.preset.js'), ], theme: { extend: { // 覆盖预设中的配置 }, }, }
最佳实践
- 使用 extend 而非覆盖:使用
extend对象扩展默认主题,避免完全覆盖 - 组织配置结构:将相关配置放在一起,保持代码清晰
- 使用语义化命名:为自定义颜色、字体等使用有意义的名称
- 版本控制配置:将配置文件纳入版本控制
- 文档化自定义配置:为团队创建配置文档
配置验证
可以使用 npx tailwindcss init --full 生成完整的配置文件模板,了解所有可配置选项。