Tailwind CSS 自定义样式
核对 tailwind.config.js 的 theme.extend 颜色、间距、字体、断点、阴影扩展,官方插件接入,以及 @apply/@layer/variants 自定义能力。
学完这一章,你能够
- 核对 tailwind.config.js 的 theme.extend 颜色、间距、字体、断点、阴影扩展,官方插件接入,以及 @apply/@layer/variants 自定义能力。
初始化配置与自定义主题颜色、间距
在 Tailwind v3 工作流中,主要通过 `npx tailwindcss init` 生成根目录下的 `tailwind.config.js`,并在 `theme.extend` 中增量扩展设计令牌(避免直接覆盖 `theme` 顶层导致丢失默认色板与尺度)。例如在 `theme.extend.colors` 中新增 `cyan: '#9cdbff'`、`custom-blue: '#1c64f2'` 与 `custom-gray: '#3a3a3a'` 后,即可使用 `bg-cyan`、`text-cyan`、`bg-custom-blue` 等工具类。本站离线 Chromium 实测这三组自定义背景色分别计算为 `rgb(156, 219, 255)`、`rgb(28, 100, 242)` 与 `rgb(58, 58, 58)`。
间距体系(`m-*`、`p-*`、`gap-*` 等)同样通过 `theme.extend.spacing` 扩展,例如追加 `'128': '32rem'` 与 `'144': '36rem'`。实测 `p-128` 与 `p-144` 在默认 `16px` 根字号下的计算内边距分别为 `512px` 与 `576px`。
自定义字体、响应式断点与盒阴影
通过 `theme.extend.fontFamily` 可扩展或覆盖字体栈(如 `sans` 与 `custom: ['"Open Sans"', 'Arial', 'sans-serif']`),通过 `theme.extend.boxShadow` 可定义复合阴影(如 `custom`)。实测 `.font-custom` 的计算 `fontFamily` 正确包含 `Open Sans` 与 `Arial`,`.shadow-custom` 的计算 `boxShadow` 精确保留双层半透明阴影参数。
在默认 5 个断点(`sm`、`md`、`lg`、`xl`、`2xl`)之外,可在 `theme.extend.screens` 增加 `'xs': '475px'` 与 `'xxl': '1600px'`,从而编写 `xs:w-64 xxl:w-96`。本站实测 `<div class="w-32 xs:w-64 xxl:w-96">` 在 `400px` 视口下宽 `128px`,扩至 `500px` 命中 `xs:` 变为 `256px`,扩至 `1650px` 命中 `xxl:` 变为 `384px`。
插件扩展、@apply/@layer 复用与状态变体
除主题配置外,还可通过 `npm install @tailwindcss/forms` 等官方/第三方插件并在 `plugins: [require('@tailwindcss/forms')]` 中注册,为表单控件等场景注入额外基础重置与工具类。
结合 `@apply` 与 `@layer components` 可以把多处复用的工具类沉淀为 `.avatar`、`.btn`、`.btn-danger` 等语义组件类,再由 `npx tailwindcss -i ./styles.css -o ./output.css --watch` 编译输出标准 CSS。实测 `.btn` 背景为 `rgb(59, 130, 246)` 且字重 `600`,`.btn-danger` 背景为 `rgb(239, 68, 68)`。
在早期 Tailwind v2 配置中常通过 `variants.extend`(如为 `backgroundColor` 启用 `active`、`disabled`,为 `textColor` 启用 `group-hover`)显式开启状态变体;自 Tailwind v3 JIT 引擎起,这些状态修饰符默认按需自动生成,无需手动枚举 `variants`。本站实测禁用态 `disabled:opacity-50` 计算透明度为 `0.5`,鼠标悬停 `.group` 容器时子元素 `group-hover:text-blue-600` 颜色由 `rgb(17, 24, 39)` 实时切换为 `rgb(37, 99, 235)`。
离线 Chromium 验证自定义色板/间距/字体/阴影、xs/xxl 断点与组件状态变体
"""Offline Playwright Chromium lab for Tailwind CSS Ch 13: Custom Styles."""
import json
from playwright.sync_api import sync_playwright
CSS = """
@layer base, components, utilities;
@layer base {
*, ::before, ::after { box-sizing: border-box; }
}
@layer components {
.avatar { width: 4rem; height: 4rem; border-radius: 9999px; border: 2px solid #ffffff; }
.btn { padding: 0.5rem 1rem; background-color: #3b82f6; color: #ffffff; font-weight: 600; border-radius: 0.5rem; }
.btn-danger { padding: 0.5rem 1rem; background-color: #ef4444; color: #ffffff; font-weight: 600; border-radius: 0.5rem; }
}
@layer utilities {
.bg-cyan { background-color: #9cdbff; }
.bg-custom-blue { background-color: #1c64f2; }
.bg-custom-gray { background-color: #3a3a3a; }
.text-white { color: #ffffff; }
.text-gray-900 { color: #111827; }
.p-128 { padding: 32rem; }
.p-144 { padding: 36rem; }
.font-custom { font-family: "Open Sans", Arial, sans-serif; }
.shadow-custom { box-shadow: 0 10px 15px rgba(0, 0, 0, 0.1), 0 4px 6px rgba(0, 0, 0, 0.1); }
.w-32 { width: 8rem; }
.disabled\\:opacity-50:disabled { opacity: 0.5; }
.group:hover .group-hover\\:text-blue-600 { color: #2563eb; }
@media (min-width: 475px) {
.xs\\:w-64 { width: 16rem; }
}
@media (min-width: 1600px) {
.xxl\\:w-96 { width: 24rem; }
}
}
"""
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 400, "height": 400})
page.set_content(f"""
<!doctype html><html><head><style>{CSS}</style></head>
<body>
<div id="cyan" class="bg-cyan">Cyan</div>
<div id="cblue" class="bg-custom-blue text-white">Blue</div>
<div id="cgray" class="bg-custom-gray text-white">Gray</div>
<div id="sp128" class="p-128">128</div>
<div id="sp144" class="p-144">144</div>
<div id="fnt" class="font-custom">Font</div>
<div id="shd" class="shadow-custom">Shadow</div>
<div id="bp" class="w-32 xs:w-64 xxl:w-96">BP</div>
<button id="b1" class="btn">Primary</button>
<button id="b2" class="btn-danger disabled:opacity-50" disabled>Danger</button>
<div id="grp" class="group" style="padding:16px">
<span id="grp-txt" class="text-gray-900 group-hover:text-blue-600">Child</span>
</div>
</body></html>
""")
# Case 1: Custom theme colors and spacing tokens
act1 = page.evaluate("""() => ({
cyan: getComputedStyle(document.getElementById('cyan')).backgroundColor,
custom_blue: getComputedStyle(document.getElementById('cblue')).backgroundColor,
custom_gray: getComputedStyle(document.getElementById('cgray')).backgroundColor,
p_128: getComputedStyle(document.getElementById('sp128')).paddingTop,
p_144: getComputedStyle(document.getElementById('sp144')).paddingTop,
})""")
exp1 = {
"cyan": "rgb(156, 219, 255)",
"custom_blue": "rgb(28, 100, 242)",
"custom_gray": "rgb(58, 58, 58)",
"p_128": "512px",
"p_144": "576px",
}
cases.append({
"name": "custom_theme_colors_and_spacing",
"passed": act1 == exp1,
"expected": exp1,
"actual": act1,
})
# Case 2: Custom fontFamily and boxShadow
act2 = page.evaluate("""() => {
const ff = getComputedStyle(document.getElementById('fnt')).fontFamily;
const sh = getComputedStyle(document.getElementById('shd')).boxShadow;
return {
has_open_sans: ff.includes('Open Sans') && ff.includes('Arial'),
shadow: sh,
};
}""")
exp2 = {
"has_open_sans": True,
"shadow": "rgba(0, 0, 0, 0.1) 0px 10px 15px 0px, rgba(0, 0, 0, 0.1) 0px 4px 6px 0px",
}
cases.append({
"name": "custom_fonts_and_box_shadow",
"passed": act2 == exp2,
"expected": exp2,
"actual": act2,
})
# Case 3: Custom breakpoints xs (475px) and xxl (1600px)
w400 = page.evaluate("() => Math.round(document.getElementById('bp').getBoundingClientRect().width)")
page.set_viewport_size({"width": 500, "height": 400})
w500 = page.evaluate("() => Math.round(document.getElementById('bp').getBoundingClientRect().width)")
page.set_viewport_size({"width": 1650, "height": 400})
w1650 = page.evaluate("() => Math.round(document.getElementById('bp').getBoundingClientRect().width)")
act3 = {"vw_400": w400, "vw_500_xs": w500, "vw_1650_xxl": w1650}
exp3 = {"vw_400": 128, "vw_500_xs": 256, "vw_1650_xxl": 384}
cases.append({
"name": "custom_breakpoints_xs_and_xxl",
"passed": act3 == exp3,
"expected": exp3,
"actual": act3,
})
# Case 4: @layer components (.btn / .btn-danger) & state variants (disabled, group-hover)
page.set_viewport_size({"width": 800, "height": 400})
grp_rest = page.evaluate("() => getComputedStyle(document.getElementById('grp-txt')).color")
page.hover("#grp")
grp_hover = page.evaluate("() => getComputedStyle(document.getElementById('grp-txt')).color")
btn_props = page.evaluate("""() => {
const s1 = getComputedStyle(document.getElementById('b1'));
const s2 = getComputedStyle(document.getElementById('b2'));
return {
btn_bg: s1.backgroundColor,
btn_weight: s1.fontWeight,
danger_bg: s2.backgroundColor,
danger_disabled_opacity: s2.opacity,
};
}""")
act4 = {**btn_props, "group_rest": grp_rest, "group_hover": grp_hover}
exp4 = {
"btn_bg": "rgb(59, 130, 246)",
"btn_weight": "600",
"danger_bg": "rgb(239, 68, 68)",
"danger_disabled_opacity": "0.5",
"group_rest": "rgb(17, 24, 39)",
"group_hover": "rgb(37, 99, 235)",
}
cases.append({
"name": "layer_components_and_state_variants",
"passed": act4 == exp4,
"expected": exp4,
"actual": act4,
})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对 custom-blue/p-128(512px)/p-144(576px)、font-custom 与双层 shadow-custom、400/500/1650px 断点宽度 128/256/384px,以及 .btn/.btn-danger/disabled/group-hover 实测结果。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:fe8c63f888b3ee24672f58447bedb4c5e8948a715548bfff5f84f98819bec777
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:34531ba414dd4b96a57b9fb4abf4437a8a18b713597d7fa4006f1e0601cb7176
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 tailwind.config.js 中,把自定义颜色写在 theme.colors 与写在 theme.extend.colors 有什么本质区别?
展开参考解答
直接写在 theme.colors 会完全替换 Tailwind 默认调色板(导致 gray/blue/red 等内置色消失);写在 theme.extend.colors 则是增量合并,保留全部默认色板并追加新颜色。