乐闻世界logo
搜索文章和话题

Tailwind CSS 配置文件 tailwind.config.js 的常用配置项有哪些?

2月17日 22:59

Tailwind CSS 的配置文件(tailwind.config.js)是自定义设计系统的核心,通过配置文件可以完全控制框架的行为。

配置文件结构:

javascript
module.exports = { content: [], // 扫描的文件路径 theme: {}, // 主题配置 plugins: [], // 插件配置 }

content 配置:

  • 指定 Tailwind 扫描的文件路径
  • 支持 glob 模式匹配
  • 示例:
    javascript
    content: [ "./src/**/*.{html,js}", "./pages/**/*.vue", "./components/**/*.jsx" ]
  • JIT 模式下,只生成使用到的类

theme 配置:

  • colors:自定义颜色
    javascript
    theme: { colors: { primary: '#3b82f6', secondary: '#10b981', 'custom-blue': { light: '#93c5fd', DEFAULT: '#3b82f6', dark: '#1d4ed8', } } }
  • spacing:自定义间距
    javascript
    theme: { spacing: { '128': '32rem', '144': '36rem', } }
  • fontSize:自定义字体大小
    javascript
    theme: { fontSize: { 'xxs': '0.75rem', 'xxl': '2.25rem', } }
  • fontFamily:自定义字体
    javascript
    theme: { fontFamily: { sans: ['Inter', 'sans-serif'], mono: ['Fira Code', 'monospace'], } }
  • extend:扩展默认主题
    javascript
    theme: { extend: { colors: { brand: '#ff6b6b', }, spacing: { '72': '18rem', } } }

plugins 配置:

  • 官方插件:
    • @tailwindcss/forms:表单样式
    • @tailwindcss/typography:排版样式
    • @tailwindcss/aspect-ratio:宽高比
    • @tailwindcss/line-clamp:文本截断
  • 安装插件:npm install -D @tailwindcss/forms
  • 使用插件:
    javascript
    plugins: [ require('@tailwindcss/forms'), require('@tailwindcss/typography'), ]

presets 配置:

  • 使用预设配置
  • 示例:
    javascript
    presets: [ require('./my-preset'), ]

darkMode 配置:

  • 'media':使用系统偏好设置
  • 'class':使用类名控制
  • 示例:
    javascript
    darkMode: 'class', // 或 'media'

corePlugins 配置:

  • 禁用核心插件
  • 示例:
    javascript
    corePlugins: { preflight: false, // 禁用基础样式重置 }

important 配置:

  • 设置 !important 优先级
  • 示例:
    javascript
    important: true, // 所有类都添加 !important // 或 important: '#app', // 在特定选择器下添加 !important

prefix 配置:

  • 为所有类添加前缀
  • 示例:
    javascript
    prefix: 'tw-', // 所有类名变为 tw-*

separator 配置:

  • 自定义类名分隔符
  • 示例:
    javascript
    separator: '_', // 使用下划线代替连字符

safelist 配置:

  • 防止某些类被清除
  • 示例:
    javascript
    safelist: [ 'bg-red-500', { pattern: /bg-(red|green|blue)-(100|200|300)/, variants: ['hover', 'focus'], } ]

最佳实践:

  • 使用 extend 而不是覆盖默认主题
  • 合理组织配置文件结构
  • 使用设计令牌保持一致性
  • 利用插件扩展功能
  • 定期审查和优化配置
标签:Tailwind CSS