颜色系统基础
1. 默认调色板
Tailwind CSS 提供了一套精心设计的默认颜色系统:
// tailwind.config.js 默认颜色示例
module.exports = {
theme: {
colors: {
// 灰度
gray: {
50: '#f9fafb',
100: '#f3f4f6',
200: '#e5e7eb',
// ... 更多色阶
900: '#111827',
},
// 主题色
blue: {
50: '#eff6ff',
100: '#dbeafe',
500: '#3b82f6',
// ... 更多色阶
900: '#1e3a8a',
},
// 其他颜色...
}
}
}
2. 颜色命名规范
- 基础色名:gray、red、blue 等
- 色阶值:50-900,数值越大越深
- 特殊颜色:white、black、transparent、current
3. 颜色使用方式
背景蓝色,文字白色
带透明度的蓝色背景
主题定制
1. 扩展默认主题
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
'brand': {
light: '#60A5FA',
DEFAULT: '#3B82F6',
dark: '#1D4ED8',
},
'accent': '#F59E0B',
}
}
}
}
2. 完全自定义主题
// tailwind.config.js
module.exports = {
theme: {
colors: {
// 完全自定义的颜色系统
primary: {
light: '#85d7ff',
DEFAULT: '#1fb6ff',
dark: '#009eeb',
},
secondary: {
light: '#ff7ce5',
DEFAULT: '#ff49db',
dark: '#ff16d1',
}
}
}
}
深色模式实现
1. 基础配置
// tailwind.config.js
module.exports = {
darkMode: 'class', // 或 'media'
}
2. 深色模式使用
自适应深色模式的标题
自适应深色模式的段落
3. 切换实现
// 切换深色模式
function toggleDarkMode() {
document.documentElement.classList.toggle('dark');
}
主题切换系统
1. 动态主题配置
// themes.js
export const themes = {
light: {
primary: '#3B82F6',
secondary: '#10B981',
background: '#FFFFFF',
text: '#111827',
},
dark: {
primary: '#60A5FA',
secondary: '#34D399',
background: '#111827',
text: '#F9FAFB',
},
}
2. CSS 变量实现
/* 根变量定义 */
:root {
--color-primary: theme('colors.blue.500');
--color-secondary: theme('colors.green.500');
}
.dark {
--color-primary: theme('colors.blue.400');
--color-secondary: theme('colors.green.400');
}
3. 组件应用
颜色系统最佳实践
1. 语义化颜色使用
// tailwind.config.js
module.exports = {
theme: {
extend: {
colors: {
// 语义化命名
'success': '#10B981',
'warning': '#F59E0B',
'error': '#EF4444',
'info': '#3B82F6',
}
}
}
}
2. 渐变色使用
渐变背景
三色渐变
3. 色彩无障碍
实战应用示例
1. 品牌色系统
2. 状态颜色
成功提示消息
警告提示消息
错误提示消息
进阶技巧
1. 动态颜色生成
// 使用 CSS 变量生成动态颜色
function generateColors(hue) {
return {
light: `hsl(${hue}, 70%, 80%)`,
DEFAULT: `hsl(${hue}, 70%, 50%)`,
dark: `hsl(${hue}, 70%, 30%)`,
}
}
2. 主题预设
// presets.js
const brandPreset = {
theme: {
colors: {
brand: {
// 品牌色预设
}
}
}
}
总结
Tailwind CSS 的颜色系统和主题定制提供了:
- 完整的默认调色板
- 灵活的自定义能力
- 深色模式支持
- 主题切换机制
通过合理运用这些特性,我们可以:
- 建立统一的品牌形象
- 提供良好的用户体验
- 实现灵活的主题切换
- 确保无障碍访问
在实际开发中,应该根据项目需求合理规划颜色系统,并建立清晰的使用规范。