Tailwind CSS自定义用法

发布于:2025-06-30 ⋅ 阅读:(16) ⋅ 点赞:(0)


前言

在 React 项目中使用 Tailwind CSS 并进行自定义样式配置,主要包括以下几种方式和步骤:


✅ 一、集成 Tailwind CSS 到 React 项目

以 Vite 项目为例,集成步骤如下:

1. 安装依赖

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

这会生成:

  • tailwind.config.js
  • postcss.config.js

2. 配置 tailwind.config.js

添加你的源码路径以启用 JIT 模式下的 tree-shaking

/** @type {import('tailwindcss').Config} */
export default {
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {}, // 用于扩展自定义样式
  },
  plugins: [],
}

3. 创建全局样式文件(如 src/index.css

@tailwind base;
@tailwind components;
@tailwind utilities;

这是 Tailwind CSS 的核心指令,用于在你的 CSS 文件中引入 Tailwind 的三大层级样式:

@tailwind base;

引入 Tailwind 的基础样式(reset/normalize、全局样式、字体、表单等)。
作用类似于 CSS Reset,保证不同浏览器下的样式一致性,并设置一些全局的基础样式。

@tailwind components;

引入 Tailwind 的组件类(如 container、按钮等可复用的组件样式)。
你也可以在这里通过 @layer components { … } 自定义自己的组件样式。

@tailwind utilities;

引入 Tailwind 的工具类(如 p-4、text-center、bg-blue-500 等)。
这些是你在 JSX/HTML 里最常用的 Tailwind 类名。

4. 在 main.tsxmain.jsx 中引入样式

import './index.css'

✅ 二、自定义样式方式汇总

1. theme.extend 自定义主题(推荐)

位置tailwind.config.js

theme: {
  extend: {
    colors: {
      primary: '#1e40af',
      danger: '#e11d48',
    },
    spacing: {
      '72': '18rem',
      '84': '21rem',
    },
    fontFamily: {
      inter: ['Inter', 'sans-serif'],
    }
  },
}

然后你可以在组件中使用:

<div className="bg-primary text-white p-4">Hello</div>

2. 添加自定义组件类(@layer)

位置index.cssglobal.css

@layer components {
  .btn-primary {
    @apply bg-blue-600 text-white px-4 py-2 rounded;
  }

  .card {
    @apply shadow-md rounded-lg p-6 bg-white;
  }
}

使用方式:

<button className="btn-primary">Click</button>

3. 插件方式自定义(如 typographyforms

npm install @tailwindcss/forms @tailwindcss/typography
plugins: [
  require('@tailwindcss/forms'),
  require('@tailwindcss/typography'),
],
扩展:

Tailwind CSS 支持通过自定义插件(Plugin)来扩展样式系统,这是构建 组件库设计系统复用工具类 的关键手段之一。下面将从 原理、语法、示例和在 React 项目中的集成步骤,手把手讲清楚 Tailwind CSS 自定义插件的用法。


✅ 一、什么是 Tailwind CSS 插件?

Tailwind 插件允许你通过 API 注册新的:

  • 工具类(utilities)
  • 组件类(components)
  • 自定义变体(variants)
  • 基础样式(base)

✅ 二、创建自定义插件的步骤

🧱 插件结构示意:

// tailwind.config.js
const plugin = require('tailwindcss/plugin')

module.exports = {
  content: [...],
  theme: {
    extend: {},
  },
  plugins: [
    plugin(function({ addUtilities, addComponents, addBase, matchUtilities, theme }) {
      // 1. 添加基础样式
      addBase({
        'h1': { fontSize: theme('fontSize.2xl') },
        'h2': { fontSize: theme('fontSize.xl') },
      })

      // 2. 添加组件类
      addComponents({
        '.btn': {
          padding: '0.5rem 1rem',
          borderRadius: '0.25rem',
          fontWeight: '600',
        },
        '.btn-primary': {
          backgroundColor: theme('colors.blue.500'),
          color: theme('colors.white'),
        },
      })

      // 3. 添加工具类
      addUtilities({
        '.text-shadow': {
          textShadow: '2px 2px #000000',
        },
        '.text-shadow-md': {
          textShadow: '4px 4px #000000',
        },
      })

      // 4. 响应式匹配工具类
      matchUtilities(
        {
          'rotate-y': (value) => ({
            transform: `rotateY(${value})`,
          }),
        },
        { values: theme('rotate') }
      )
    })
  ],
}

✅ 三、React 项目中使用该插件

只需将上面的 tailwind.config.js 插件注册完成后,像平常一样使用样式类:

<button className="btn btn-primary text-shadow-md">Click Me</button>

无需其他导入!Tailwind 会自动根据你 content 中匹配到的类,生成 CSS。


✅ 四、高阶用法:插件封装为 NPM 包(组件库开发)

你可以将插件封装成独立模块:

// my-button-plugin.js
const plugin = require('tailwindcss/plugin')

module.exports = plugin(({ addComponents, theme }) => {
  addComponents({
    '.btn-danger': {
      backgroundColor: theme('colors.red.500'),
      color: '#fff',
      padding: '0.5rem 1rem',
      borderRadius: '9999px',
    },
  })
})

然后在主配置中使用:

const myButtonPlugin = require('./my-button-plugin')

module.exports = {
  plugins: [myButtonPlugin],
}

✅ 五、自定义插件使用场景总结

场景 使用方式
提供通用按钮/卡片/警告样式 addComponents
增强工具类(如旋转、投影) addUtilities
改变基础标签默认样式 addBase
动态类支持(如 .rotate-y-45 matchUtilities

✅ 是否支持 TypeScript?

Tailwind 插件本质是 JS 函数,也可以使用 .ts 文件编写,只要你在 tailwind.config.ts 中用 defineConfig() 包裹即可:

import plugin from 'tailwindcss/plugin'
import { defineConfig } from 'tailwindcss/helpers'

export default defineConfig({
  plugins: [
    plugin(({ addUtilities }) => {
      addUtilities({
        '.skew-10deg': {
          transform: 'skewY(-10deg)'
        }
      })
    })
  ]
})

4. 创建响应式自定义类

extend: {
  screens: {
    'xs': '480px',
  },
  maxWidth: {
    '8xl': '90rem',
  },
}

5. 使用 cva(class-variance-authority)封装组件样式(推荐大项目)

import { cva } from 'class-variance-authority'

const button = cva('px-4 py-2 rounded', {
  variants: {
    intent: {
      primary: 'bg-blue-600 text-white',
      secondary: 'bg-gray-600 text-white',
    },
    size: {
      sm: 'text-sm',
      lg: 'text-lg',
    },
  },
  defaultVariants: {
    intent: 'primary',
    size: 'sm',
  },
})

✅ 三、Tailwind CSS 常见优化建议

  • ✅ 启用 JIT 模式(默认)
  • ✅ 用 @apply 抽离公共类
  • ✅ 使用 cva 管理组件变体
  • ✅ 移除未使用的类:purge(旧)→ content(新)
  • ✅ 使用 Tailwind plugin 编写通用组件或设计系统


网站公告

今日签到

点亮在社区的每一天
去签到