蓝色天空网mbsky.com · 知识 · 实践 · 创造Tailwind CSS · 本地阅读预览
教程 / 前端开发 / Tailwind CSS

Tailwind CSS 配置

系统核对 tailwind.config.js 生成方式、content 扫描路径、theme 覆盖与 extend 扩展区别、darkMode、variants 演进、plugins 编写及全部 22 项核心配置键实测。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

配置文件初始化与基本结构

在 Tailwind CSS 3 工程中,`tailwind.config.js` 是定制设计系统的核心配置文件,可统一管理颜色、间距、字体、圆角与断点(Tailwind CSS 4 起默认改为 CSS 优先的 `@theme` 语法,仍支持通过 `@config` 加载传统 JS 配置)。在项目根目录运行 `npx tailwindcss init` 即可生成一份基础配置文件。

一份标准的 `tailwind.config.js` 导出包含 `content`、`theme`(含 `extend`)与 `plugins` 三个核心字段的配置对象。例如将 `content` 设为 `["./src/**/*.{html,js,vue}"]` 会指示编译器扫描 `src` 目录下全部 `.html`、`.js` 与 `.vue` 模板文件。

核心配置项:content、theme、darkMode、variants 与 plugins

第一项 `content` 决定 Tailwind 从哪些模板文件提取类名,可同时列出单文件(如 `./index.html`)与多扩展名 glob(如 `./src/**/*.{html,js,ts,jsx,tsx}`)。仅被扫描到的类名才会进入输出 CSS,从而大幅压缩产物体积。本站离线路径扫描实测:配置该规则后精确命中 `index.html`、`src/App.vue` 与 `src/components/Card.tsx` 并提取 5 个类名,未命中 `src/README.md` 中的测试类。

第二项 `theme` 负责定制设计令牌。写在 `theme.extend` 下会保留内置默认值并增量追加新键,例如添加 `cyan: '#9cdbff'`、嵌套品牌色 `brand: { light: '#93C5FD', DEFAULT: '#3B82F6', dark: '#1E40AF' }`、间距 `18: '4.5rem'`、字号 `'4xl': '2.5rem'` 与圆角 `'xl': '1.5rem'`;若直接写在 `theme.colors` 下则会整体替换默认调色板。配合 `darkMode: 'class'`(或 `'media'`)可声明 `bg-background-light dark:bg-background-dark`。本站离线 Chromium 实测:`bg-brand` 为 `rgb(59, 130, 246)`、`text-brand-light` 为 `rgb(147, 197, 253)`、`p-18` 为 `72px`、`text-4xl` 为 `40px`、`rounded-xl` 为 `24px`、`bg-cyan` 为 `rgb(156, 219, 255)`,开启 `.dark` 后背景由 `rgb(255, 255, 255)` 切至 `rgb(0, 0, 0)`。

第三项 `variants` 曾在 Tailwind CSS v2 用于手动开启特定属性的 `focus-visible`、`disabled` 等状态变体(自 v3 JIT 引擎及 v4 起所有变体已默认按需启用,`variants` 仅见于旧版迁移项目)。第四项 `plugins` 用于加载官方/社区插件(如 `@tailwindcss/forms`、`@tailwindcss/typography`)或用 `require('tailwindcss/plugin')` 调用 `addUtilities` 注册自定义工具类(如 `.text-shadow`)。本站离线 Chromium 实测自定义 `.text-shadow` 计算为 `rgba(0, 0, 0, 0.5) 2px 2px 4px`,禁用态 `disabled:opacity-40` 计算为 `0.4`。

完整配置模板与全量选项参考

默认情况下 Tailwind 会自动读取项目根目录的 `tailwind.config.js`,既可通过顶层 `theme.colors`、`theme.fontFamily` 全面接管品牌色板与字体栈,也可在 `theme.extend` 中追加 `8xl`/`9xl` 间距与 `4xl` 圆角(实测 `rounded-4xl` 为 `32px`)。本站还在 Chromium 中实测了全量参考表中的自定义属性:`2xl:text-4xl` 在 `1280px` 为 `16px`、达 `1536px` 切为 `40px`;`border-3` 为 `3px`、`z-max` 为 `9999`、`opacity-40` 为 `0.4`、`aspect-[16/9]` 在 `320px` 宽下高 `180px`、`duration-400` 为 `0.4s`。合理组合 `extend`、`theme` 与 `plugins`,能让团队设计规范与代码实现保持高度一致。

theme 常用扩展配置项速览

配置项描述示例
fontSize自定义字号尺度映射fontSize: { 'xs': '0.75rem', '4xl': '2.5rem' }
screens自定义响应式断点阈值screens: { 'sm': '640px', 'xl': '1280px' }
borderRadius自定义元素圆角半径borderRadius: { 'lg': '1rem', 'xl': '1.5rem' }
extend在不覆盖默认主题的前提下追加或覆盖指定键extend: { colors: { danger: '#FF5A5F' } }

tailwind.config.js 完整配置项参考

配置项描述默认值参考配置示例
content声明待扫描的模板文件路径以按需生成样式['./src/**/*.{html,js,ts,jsx,tsx}']content: ['./src/**/*.html', './src/**/*.vue']
theme定义或替换 Tailwind 默认设计系统(颜色、间距、字体等)extend: {}theme: { colors: { primary: '#3490dc' } }
extend在保留默认主题配置的基础上进行增量扩展{}extend: { colors: { primary: '#3490dc' } }
screens配置移动优先响应式断点阈值{ sm: '640px', md: '768px', lg: '1024px', xl: '1280px' }screens: { '2xl': '1536px' }
colors替换或扩展调色板色值(支持嵌套 DEFAULT 键)内置 slate/blue/red/green 等完整色板colors: { primary: '#1D4ED8', secondary: '#64748B' }
spacing统一控制 padding、margin、width、height、gap 间距尺度以 0.25rem 为步进的默认尺度(如 0.5rem、1rem、2rem)spacing: { 18: '4.5rem' }
fontFamily配置无衬线、衬线及等宽字体栈'sans', 'serif', 'mono'fontFamily: { sans: ['Inter', 'sans-serif'] }
fontSize配置字号及其配套行高'sm': '0.875rem', 'lg': '1.125rem' 等fontSize: { '4xl': '2.5rem' }
fontWeight配置字重数值映射thin(100) 至 black(900) 标准字重fontWeight: { light: '300', bold: '700' }
lineHeight配置文本行高比例或固定值'none': '1', 'tight': '1.25', 'normal': '1.5', 'loose': '2'lineHeight: { relaxed: '1.75', loose: '2' }
borderRadius配置圆角半径尺度'none': '0px', 'sm': '0.125rem', 'md': '0.375rem', 'lg': '0.5rem'borderRadius: { xl: '1.5rem' }
borderWidth配置边框宽度尺度{ DEFAULT: '1px', '0': '0px', '2': '2px' }borderWidth: { '3': '3px' }
zIndex配置层叠上下文 z-index 层级值{ '0': '0', '10': '10', '20': '20' }zIndex: { max: '9999' }
opacity配置透明度数值刻度{ '0': '0', '25': '0.25', '50': '0.5', '75': '0.75', '100': '1' }opacity: { '40': '0.4' }
boxShadow配置盒子投影层次样式sm / DEFAULT / md / lg / xl 等阴影预设boxShadow: { lg: '0 10px 15px -3px rgba(0, 0, 0, 0.1)' }
container配置响应式容器是否自动居中及默认水平内边距{ center: false, padding: '0' }container: { center: true, padding: '1rem' }
aspectRatio配置元素宽高比(aspect-*)映射{ auto: 'auto', square: '1 / 1', video: '16 / 9' }aspectRatio: { '16/9': '16 / 9' }
gridTemplateColumns配置 CSS Grid 列模板定义1 至 12 列及 none / subgridgridTemplateColumns: { layout: 'repeat(3, 1fr)' }
gridColumn配置网格项跨列规则(col-span-*)'span-1': 'span 1 / span 1' 等gridColumn: { 'span-2': 'span 2 / span 2' }
transitionProperty配置触发过渡动画的 CSS 属性集合默认包含 colors/opacity/shadow/transform 等transitionProperty: { color: 'color' }
transitionDuration配置过渡动画持续时长{ 75: '75ms', 150: '150ms', 300: '300ms' }transitionDuration: { '400': '400ms' }
transitionTimingFunction配置过渡缓动时间函数{ linear: 'linear', in: ..., out: ..., 'in-out': ... }transitionTimingFunction: { 'ease-out': 'ease-out' }

离线核验 content 模板扫描、theme.extend 与覆盖差异、暗色配置及自定义插件渲染

python · 阅读源码
"""Offline Playwright Chromium lab for Tailwind CSS Ch 07 (config)."""
import json
import os
import re
import tempfile
from pathlib import Path
from playwright.sync_api import sync_playwright

CONFIG_CSS = """
*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; font-family: Inter, sans-serif; font-size: 16px; }
.bg-cyan { background-color: #9cdbff; }
.bg-primary { background-color: #1d4ed8; }
.bg-secondary { background-color: #64748b; }
.bg-danger { background-color: #ff5a5f; }
.bg-brand { background-color: #3b82f6; }
.text-brand-light { color: #93c5fd; }
.text-brand-dark { color: #1e40af; }
.p-18 { padding: 4.5rem; }
.text-4xl { font-size: 2.5rem; }
.rounded-xl { border-radius: 1.5rem; }
.rounded-4xl { border-radius: 2rem; }
.border-3 { border-width: 3px; border-style: solid; border-color: #334155; }
.z-max { z-index: 9999; position: relative; }
.opacity-40 { opacity: 0.4; }
.aspect-16-9 { aspect-ratio: 16 / 9; width: 320px; }
.duration-400 { transition-property: color; transition-duration: 400ms; transition-timing-function: ease-out; }
.container { width: 100%; margin-left: auto; margin-right: auto; padding-left: 1rem; padding-right: 1rem; }
.bg-background-light { background-color: #ffffff; }
.dark .dark\\:bg-background-dark { background-color: #000000; }
.text-shadow { text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5); }
.disabled\\:opacity-40:disabled { opacity: 0.4; }
.focus-visible\\:border-primary:focus-visible { border-color: #1d4ed8; }
@media (min-width: 640px) { .sm\\:p-18 { padding: 4.5rem; } }
@media (min-width: 1536px) { .\\32xl\\:text-4xl { font-size: 2.5rem; } }
"""


def launch_browser(p):
    exe = p.chromium.executable_path
    if exe and os.path.exists(exe):
        return p.chromium.launch(headless=True)
    for ch in ("chrome", "msedge"):
        try:
            return p.chromium.launch(channel=ch, headless=True)
        except Exception:
            continue
    return p.chromium.launch(headless=True)


def run():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 1280, "height": 720})

        # Case 1: content glob scanning across html/js/ts/jsx/tsx/vue
        with tempfile.TemporaryDirectory() as tmp:
            root = Path(tmp)
            (root / "src/components").mkdir(parents=True)
            (root / "index.html").write_text('<div class="bg-brand text-brand-light">Root</div>', encoding="utf-8")
            (root / "src/App.vue").write_text('<template><div class="p-18 rounded-xl">Vue</div></template>', encoding="utf-8")
            (root / "src/components/Card.tsx").write_text('export const Card = () => <div className="text-shadow">TSX</div>;', encoding="utf-8")
            (root / "src/README.md").write_text('<div class="bg-unused">Docs</div>', encoding="utf-8")

            exts = {".html", ".js", ".ts", ".jsx", ".tsx", ".vue"}
            matched = []
            if (root / "index.html").exists():
                matched.append("index.html")
            for f in sorted((root / "src").rglob("*")):
                if f.is_file() and f.suffix in exts:
                    matched.append(f.relative_to(root).as_posix())
            classes = set()
            for rel in matched:
                txt = (root / rel).read_text(encoding="utf-8")
                for m in re.findall(r'(?:class|className)="([^"]+)"', txt):
                    classes.update(m.split())

            actual1 = {
                "matchedFiles": matched,
                "excludedReadme": "bg-unused" not in classes,
                "extractedClasses": sorted(classes),
            }
            expected1 = {
                "matchedFiles": ["index.html", "src/App.vue", "src/components/Card.tsx"],
                "excludedReadme": True,
                "extractedClasses": ["bg-brand", "p-18", "rounded-xl", "text-brand-light", "text-shadow"],
            }
            cases.append(dict(
                name="content_glob_scanning",
                expected=expected1,
                actual=actual1,
                passed=(actual1 == expected1),
            ))

        # Case 2: theme.extend custom tokens vs direct theme override semantics
        default_colors = {"blue": "#3b82f6", "red": "#ef4444", "green": "#22c55e"}
        extended_colors = {**default_colors, "cyan": "#9cdbff", "primary": "#1d4ed8"}
        overridden_colors = {"blue": "#1fb6ff", "purple": "#7e5bef"}
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{CONFIG_CSS}</style></head>
<body>
  <div id="brand" class="bg-brand text-brand-light p-18 text-4xl rounded-xl">Custom Brand</div>
  <div id="cyan" class="bg-cyan rounded-4xl">Cyan</div>
</body></html>""")
        actual2 = page.evaluate("""(meta) => {
            const sb = getComputedStyle(document.getElementById('brand'));
            const sc = getComputedStyle(document.getElementById('cyan'));
            return {
                brandBg: sb.backgroundColor,
                brandColor: sb.color,
                spacing18: sb.paddingTop,
                fontSize4xl: sb.fontSize,
                radiusXl: sb.borderRadius,
                cyanBg: sc.backgroundColor,
                radius4xl: sc.borderRadius,
                extendKeepsRed: meta.extendKeepsRed,
                overrideDropsRed: meta.overrideDropsRed,
            };
        }""", {
            "extendKeepsRed": "red" in extended_colors,
            "overrideDropsRed": "red" not in overridden_colors,
        })
        expected2 = {
            "brandBg": "rgb(59, 130, 246)",
            "brandColor": "rgb(147, 197, 253)",
            "spacing18": "72px",
            "fontSize4xl": "40px",
            "radiusXl": "24px",
            "cyanBg": "rgb(156, 219, 255)",
            "radius4xl": "32px",
            "extendKeepsRed": True,
            "overrideDropsRed": True,
        }
        cases.append(dict(
            name="theme_extend_vs_override",
            expected=expected2,
            actual=actual2,
            passed=(actual2 == expected2),
        ))

        # Case 3: darkMode: 'class', custom screens (2xl), and full config token properties
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{CONFIG_CSS}</style></head>
<body>
  <div id="dm" class="bg-background-light dark:bg-background-dark">Dark</div>
  <div id="box" class="border-3 z-max opacity-40 aspect-16-9 duration-400">Props</div>
  <div id="scr" class="2xl:text-4xl">Screen</div>
</body></html>""")
        light_bg = page.eval_on_selector("#dm", "el => getComputedStyle(el).backgroundColor")
        page.evaluate("document.documentElement.classList.add('dark')")
        dark_bg = page.eval_on_selector("#dm", "el => getComputedStyle(el).backgroundColor")
        fs_1280 = page.eval_on_selector("#scr", "el => getComputedStyle(el).fontSize")
        page.set_viewport_size({"width": 1536, "height": 720})
        fs_1536 = page.eval_on_selector("#scr", "el => getComputedStyle(el).fontSize")
        box_props = page.eval_on_selector("#box", """el => {
            const s = getComputedStyle(el);
            const r = el.getBoundingClientRect();
            return {
                borderWidth: s.borderTopWidth,
                zIndex: s.zIndex,
                opacity: s.opacity,
                aspectHeightPx: Math.round(r.height),
                transitionDuration: s.transitionDuration,
            };
        }""")
        actual3 = {
            "lightBg": light_bg,
            "darkBg": dark_bg,
            "fontSizeAt1280": fs_1280,
            "fontSizeAt1536": fs_1536,
            **box_props,
        }
        expected3 = {
            "lightBg": "rgb(255, 255, 255)",
            "darkBg": "rgb(0, 0, 0)",
            "fontSizeAt1280": "16px",
            "fontSizeAt1536": "40px",
            "borderWidth": "3px",
            "zIndex": "9999",
            "opacity": "0.4",
            "aspectHeightPx": 180,
            "transitionDuration": "0.4s",
        }
        cases.append(dict(
            name="dark_mode_and_config_tokens",
            expected=expected3,
            actual=actual3,
            passed=(actual3 == expected3),
        ))

        # Case 4: Custom plugin addUtilities (.text-shadow) & disabled/focus-visible variants
        page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{CONFIG_CSS}</style></head>
<body>
  <h2 id="sh" class="text-shadow">Shadowed</h2>
  <button id="dis" class="disabled:opacity-40" disabled>Disabled</button>
</body></html>""")
        actual4 = page.evaluate("""() => ({
            textShadow: getComputedStyle(document.getElementById('sh')).textShadow,
            disabledOpacity: getComputedStyle(document.getElementById('dis')).opacity,
        })""")
        expected4 = {
            "textShadow": "rgba(0, 0, 0, 0.5) 2px 2px 4px",
            "disabledOpacity": "0.4",
        }
        cases.append(dict(
            name="plugin_add_utilities_and_variants",
            expected=expected4,
            actual=actual4,
            passed=(actual4 == expected4),
        ))

        browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    run()
预期结果 · 待实际运行核验
  • 核对 6 类模板扩展名过滤、brand/cyan/spacing-18/4xl/rounded-xl 计算值、darkMode class 切换、2xl 断点、border-3/z-max/opacity-40/16:9/400ms 与 text-shadow 插件。
离线核验 content 模板扫描、theme.extend 与覆盖差异、暗色配置及自定义插件渲染

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:f11e6edd56d50f0af87a5e72daa1f09bd3f901136028d010981b2f6d196640a3

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Tailwind CSS 配置实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:ceb0957e34d62dbac9d762bbbf981f096c89544688200dab7f87e20e386d88f5

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

将自定义颜色写在 `theme.colors` 与写在 `theme.extend.colors` 中会带来什么截然不同的结果?

展开参考解答

直接写在 `theme.colors` 会完全覆盖 Tailwind 内置的整套默认调色板(导致原有 `blue-500` 等类不可用);写在 `theme.extend.colors` 则会保留全部默认色板并增量合并自定义颜色。

规范与官方依据