Tailwind CSS 状态处理
系统核对悬停/聚焦/激活、组合状态、结构伪类(first/last/odd/even)、表单状态、group 父级联动、响应式暗色叠加、variants 演进及 23 项修饰符参考与 Chromium 实测。
学完这一章,你能够
- 系统核对悬停/聚焦/激活、组合状态、结构伪类(first/last/odd/even)、表单状态、group 父级联动、响应式暗色叠加、variants 演进及 23 项修饰符参考与 Chromium 实测。
交互状态修饰符:悬停、聚焦、激活与焦点内
Tailwind CSS 通过在工具类前添加状态修饰符(如 `hover:`、`focus:`、`active:`、`visited:`、`focus-within:`),让开发者直接在 HTML 中声明交互反馈而无需手写伪类 CSS 规则。
悬停状态使用 `hover:{class}` 语法(例如 `hover:bg-sky-700`、`hover:text-white`、`hover:underline`、`hover:border-2 hover:border-gray-500`)。对按钮 `px-4 py-2 bg-blue-500 text-white hover:bg-sky-700` 执行真实悬停,本站离线 Chromium 实测背景由 `rgb(59, 130, 246)` 变为 `rgb(3, 105, 161)`。
聚焦状态使用 `focus:{class}`(如 `focus:outline-none focus:ring-2 focus:ring-blue-600`、`focus:text-black`、`focus:border-blue-500`、`focus:ring-4 focus:ring-opacity-50 focus:ring-green-500`)。对输入框执行 `focus()` 后,Chromium 实测聚焦环阴影为 `rgb(37, 99, 235) 0px 0px 0px 2px`,同时包裹该输入框的 `focus-within:border-blue-500` 父容器边框色即时切换为 `rgb(59, 130, 246)`。
激活状态使用 `active:{class}` 控制元素被按下瞬间的视觉反馈(如 `active:bg-green-700`、`active:text-gray-600`、`active:ring-2 active:ring-opacity-50 active:ring-green-500`)。在 Chromium 中对按钮执行鼠标按下(`mouse.down()`),背景色精确切换为 `rgb(21, 128, 61)`。
组合状态、响应式与暗色叠加及 variants 演进
多个修饰符可以按 `{condition}:{state}:{class}` 串联组合(例如 `dark:md:hover:bg-fuchsia-600`、`sm:focus:ring-2`、`lg:active:bg-red-500`)。对按钮 `hover:bg-sky-700 dark:hover:bg-fuchsia-600` 实测:浅色模式悬停为 `rgb(3, 105, 161)`,启用 `.dark` 后悬停切换为 `rgb(192, 38, 211)`。
将响应式前缀(`sm:`、`md:`、`lg:`、`xl:`、`2xl:`)与 `dark:`、交互态组合时,如 `dark:bg-gray-800 sm:hover:bg-blue-700 md:focus:ring-2 md:focus:ring-blue-500`,本站离线 Chromium 在 `768px` 暗色视口实测默认深灰 `rgb(31, 41, 55)`、悬停切为 `rgb(29, 78, 216)`、聚焦呈现 `2px` 蓝色外环。关于 `tailwind.config.js` 中的 `variants.extend`(为 `backgroundColor` 开启 `active`/`group-hover`、为 `textColor` 开启 `focus-visible`/`disabled`):这是 Tailwind v2 所需的显式开关,自 v3 JIT 与 v4 起所有状态修饰符均已自动按需生成。
结构伪类、表单状态与父级 Group 联动
结构伪类修饰符对应 CSS 子元素位置选择器:在 Tailwind 中实际写作 `first:`(`:first-child`)、`last:`(`:last-child`)、`odd:`(`:nth-child(odd)`,基于 1 计数的第 1、3、5 项)与 `even:`(`:nth-child(even)`,第 2、4、6 项)。实践时务必将相应修饰符写在会命中的子元素上(通常循环渲染时统一附在所有 `<li>` 上,而非只给第 2 项写 `odd:`)。本站离线 Chromium 在 4 项 `<ul>` 与空 `<div>` 上实测:第 1 项文字变红 `rgb(239, 68, 68)`、第 4 项加粗 `700`、第 1 与第 3 项背景为浅灰 `rgb(243, 244, 246)`、第 2 与第 4 项背景为深灰 `rgb(229, 231, 235)`,空容器 `empty:bg-gray-50` 命中 `rgb(249, 250, 251)`。
表单状态修饰符涵盖 `required:`、`invalid:`、`disabled:`、`enabled:` 与 `checked:`。Chromium 实测中,格式非法的必填邮箱框命中 `invalid:border-yellow-500`(`rgb(234, 179, 8)`),合法必填框命中 `required:border-red-500`(`rgb(239, 68, 68)`),禁用输入框命中 `disabled:bg-gray-300`(`rgb(209, 213, 219)`)与 `opacity: 0.5`,启用框命中 `enabled:border-blue-500`。此外,在父元素标注 `group` 后,子元素可用 `group-hover:`、`group-focus:` 响应父级状态:将鼠标悬停于父容器空白区域时,子按钮背景精确由 `rgb(59, 130, 246)` 切为 `rgb(209, 213, 219)`。下表同时列出全部 23 项常用修饰符,并在 Chromium 中核验了 `before:`/`after:` 伪元素、`rtl:`、`aria-checked:`、`:target` 锚点及 `motion-safe:` 媒体偏好响应。
核心交互状态前缀速查
| 状态 | 前缀 | 作用 |
| 悬停状态 | hover: | 控制鼠标指针悬停在元素上方时的样式变化 |
| 聚焦状态 | focus: | 控制表单控件或可聚焦元素获得焦点时的样式 |
| 激活状态 | active: | 控制元素正被点击或按压期间的瞬时样式 |
| 访问状态 | visited: | 控制浏览器历史中已访问超链接的颜色样式 |
| 焦点内状态 | focus-within: | 当父容器内任意后代元素获得焦点时改变父容器样式 |
| 各状态组合 | 无特定前缀 | 按需串联多个前缀(如 dark:sm:hover:、md:focus:)实现精细控制 |
Tailwind CSS 常用修饰符与 CSS 规则完整对照表
| Modifier | CSS 对应伪类/伪元素或规则 | 说明 | 示例代码 |
| hover | :hover | 鼠标悬停时生效 | <button class="hover:bg-blue-500">Hover me</button> |
| focus | :focus | 元素获得焦点时生效 | <input class="focus:ring-2 focus:ring-blue-600" /> |
| focus-within | :focus-within | 父容器内任意子元素获得焦点时生效 | <div class="focus-within:border-blue-500"><input /></div> |
| focus-visible | :focus-visible | 仅在键盘导航或辅助技术触发焦点时生效 | <input class="focus-visible:ring-2 focus-visible:ring-blue-600" /> |
| active | :active | 元素被按下或处于活动状态时生效 | <button class="active:bg-green-700">Click me</button> |
| visited | :visited | 用户已访问过的超链接(受浏览器隐私策略限制可改属性) | <a class="visited:text-purple-600" href="#">Visited link</a> |
| target | :target | URL 哈希片段匹配当前元素 id 时生效 | <div id="section" class="target:bg-yellow-500"></div> |
| first | :first-child | 匹配父容器中的第一个子元素 | <ul><li class="first:text-red-500">First</li><li>Other</li></ul> |
| last | :last-child | 匹配父容器中的最后一个子元素 | <ul><li>Other</li><li class="last:font-bold">Last</li></ul> |
| odd | :nth-child(odd) | 匹配奇数位置子元素(从 1 开始计数) | <ul><li class="odd:bg-gray-100">Odd</li><li>Even</li></ul> |
| even | :nth-child(even) | 匹配偶数位置子元素(从 1 开始计数) | <ul><li>Odd</li><li class="even:bg-gray-200">Even</li></ul> |
| empty | :empty | 匹配不包含任何子节点与文本内容的元素 | <div class="empty:bg-gray-50"></div> |
| disabled | :disabled | 匹配处于禁用状态的表单控件 | <button class="disabled:opacity-50" disabled>Disabled</button> |
| enabled | :enabled | 匹配处于可用状态的表单控件 | <input class="enabled:border-blue-500" /> |
| checked | :checked | 匹配已勾选的复选框或单选按钮 | <input type="checkbox" class="checked:bg-blue-500" checked /> |
| required | :required | 匹配带有 required 属性的必填表单字段 | <input class="required:border-red-500" required /> |
| before | ::before | 在元素内容之前生成并修饰伪元素 | <div class="before:content-['*'] before:text-red-500"></div> |
| after | ::after | 在元素内容之后生成并修饰伪元素 | <div class="after:content-['!'] after:text-green-500"></div> |
| sm | @media (min-width: 640px) | 视口宽度大于等于 640px 时生效 | <div class="sm:bg-blue-100">Resize to small screen</div> |
| dark | @media (prefers-color-scheme: dark) 或 .dark | 系统或类触发暗色模式时生效 | <div class="dark:bg-black dark:text-white">Dark mode content</div> |
| rtl | [dir="rtl"] | 文本方向为从右到左时生效 | <div dir="rtl" class="rtl:text-right">Right to Left</div> |
| aria-checked | [aria-checked="true"] | 元素具备 aria-checked="true" 无障碍属性时生效 | <div aria-checked="true" class="aria-checked:bg-green-500">Checked</div> |
| motion-safe | @media (prefers-reduced-motion: no-preference) | 用户未开启“减少动态效果”系统偏好时启用动画 | <div class="motion-safe:transition-transform motion-safe:duration-500"></div> |
离线 Chromium 核验交互态、组合态、结构伪类、表单/Group 联动与伪元素/媒体偏好修饰符
展开查看收起
"""Offline Playwright Chromium lab for Tailwind CSS Ch 09 (state)."""
import json
import os
from playwright.sync_api import sync_playwright
TW_CSS = """
*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; font-size: 16px; }
ul { list-style: none; margin: 0; padding: 0; }
.px-4 { padding-left: 1rem; padding-right: 1rem; }
.py-2 { padding-top: 0.5rem; padding-bottom: 0.5rem; }
.p-2 { padding: 0.5rem; }
.bg-blue-500 { background-color: #3b82f6; }
.text-white { color: #ffffff; }
.border { border-width: 1px; border-style: solid; border-color: #d1d5db; }
.hover\\:bg-sky-700:hover { background-color: #0369a1; }
.active\\:bg-green-700:active { background-color: #15803d; }
.focus\\:outline-none:focus { outline: 2px solid transparent; outline-offset: 2px; }
.focus\\:ring-2:focus { --tw-ring-width: 2px; box-shadow: 0 0 0 var(--tw-ring-width) var(--tw-ring-color, #2563eb); }
.focus\\:ring-blue-600:focus { --tw-ring-color: #2563eb; }
.focus-within\\:border-blue-500:focus-within { border-color: #3b82f6; }
.dark .dark\\:bg-gray-800 { background-color: #1f2937; }
.dark .dark\\:hover\\:bg-fuchsia-600:hover { background-color: #c026d3; }
@media (min-width: 640px) {
.sm\\:hover\\:bg-blue-700:hover { background-color: #1d4ed8; }
}
@media (min-width: 768px) {
.md\\:focus\\:ring-2:focus { box-shadow: 0 0 0 2px #3b82f6; }
}
.first\\:text-red-500:first-child { color: #ef4444; }
.first\\:font-bold:first-child { font-weight: 700; }
.last\\:font-bold:last-child { font-weight: 700; }
.last\\:font-light:last-child { font-weight: 300; }
.odd\\:bg-gray-100:nth-child(odd) { background-color: #f3f4f6; }
.even\\:bg-gray-200:nth-child(even) { background-color: #e5e7eb; }
.empty\\:bg-gray-50:empty { background-color: #f9fafb; }
.required\\:border-red-500:required { border-color: #ef4444; }
.invalid\\:border-yellow-500:invalid { border-color: #eab308; }
.disabled\\:bg-gray-300:disabled { background-color: #d1d5db; }
.disabled\\:opacity-50:disabled { opacity: 0.5; }
.enabled\\:border-blue-500:enabled { border-color: #3b82f6; }
.checked\\:bg-blue-500:checked { background-color: #3b82f6; }
.group:hover .group-hover\\:bg-gray-300 { background-color: #d1d5db; }
.before\\:content-star::before { content: '*'; color: #ef4444; }
.after\\:content-bang::after { content: '!'; color: #22c55e; }
[dir="rtl"] .rtl\\:text-right, .rtl\\:text-right[dir="rtl"] { text-align: right; }
.aria-checked\\:bg-green-500[aria-checked="true"] { background-color: #22c55e; }
.target\\:bg-yellow-500:target { background-color: #eab308; }
@media (prefers-reduced-motion: no-preference) {
.motion-safe\\:duration-500 { transition-duration: 500ms; }
}
"""
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": 800, "height": 600})
# Case 1: hover, focus, active, focus-within
page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
<button id="bh" class="px-4 py-2 bg-blue-500 text-white hover:bg-sky-700">Hover</button>
<button id="ba" class="px-4 py-2 bg-blue-500 text-white active:bg-green-700">Click</button>
<div id="fw" class="border p-2 focus-within:border-blue-500">
<input id="fi" class="border p-2 focus:outline-none focus:ring-2 focus:ring-blue-600" type="text" />
</div>
</body></html>""")
bh_def = page.eval_on_selector("#bh", "el => getComputedStyle(el).backgroundColor")
page.hover("#bh")
bh_hov = page.eval_on_selector("#bh", "el => getComputedStyle(el).backgroundColor")
box = page.locator("#ba").bounding_box()
page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2)
page.mouse.down()
ba_act = page.eval_on_selector("#ba", "el => getComputedStyle(el).backgroundColor")
page.mouse.up()
page.focus("#fi")
fi_ring = page.eval_on_selector("#fi", "el => getComputedStyle(el).boxShadow")
fw_border = page.eval_on_selector("#fw", "el => getComputedStyle(el).borderTopColor")
actual1 = {
"hoverDefault": bh_def,
"hoverActive": bh_hov,
"activeBg": ba_act,
"focusRingShadow": fi_ring,
"focusWithinBorder": fw_border,
}
expected1 = {
"hoverDefault": "rgb(59, 130, 246)",
"hoverActive": "rgb(3, 105, 161)",
"activeBg": "rgb(21, 128, 61)",
"focusRingShadow": "rgb(37, 99, 235) 0px 0px 0px 2px",
"focusWithinBorder": "rgb(59, 130, 246)",
}
cases.append(dict(
name="hover_focus_active_interactions",
expected=expected1,
actual=actual1,
passed=(actual1 == expected1),
))
# Case 2: Combined dark + responsive + interactive states
page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
<button id="cb" class="px-4 py-2 bg-blue-500 text-white hover:bg-sky-700 dark:hover:bg-fuchsia-600">Combo</button>
<button id="rb" class="px-4 py-2 bg-blue-500 text-white dark:bg-gray-800 sm:hover:bg-blue-700 md:focus:ring-2">RespDark</button>
</body></html>""")
page.hover("#cb")
light_hover = page.eval_on_selector("#cb", "el => getComputedStyle(el).backgroundColor")
page.evaluate("document.documentElement.classList.add('dark')")
page.hover("#cb")
dark_hover = page.eval_on_selector("#cb", "el => getComputedStyle(el).backgroundColor")
page.set_viewport_size({"width": 768, "height": 600})
rb_dark_bg = page.eval_on_selector("#rb", "el => getComputedStyle(el).backgroundColor")
page.hover("#rb")
rb_sm_hover = page.eval_on_selector("#rb", "el => getComputedStyle(el).backgroundColor")
page.focus("#rb")
rb_md_focus = page.eval_on_selector("#rb", "el => getComputedStyle(el).boxShadow")
actual2 = {
"lightHover": light_hover,
"darkHover": dark_hover,
"respDarkBg": rb_dark_bg,
"smHoverBg": rb_sm_hover,
"mdFocusRing": rb_md_focus,
}
expected2 = {
"lightHover": "rgb(3, 105, 161)",
"darkHover": "rgb(192, 38, 211)",
"respDarkBg": "rgb(31, 41, 55)",
"smHoverBg": "rgb(29, 78, 216)",
"mdFocusRing": "rgb(59, 130, 246) 0px 0px 0px 2px",
}
cases.append(dict(
name="combined_responsive_dark_states",
expected=expected2,
actual=actual2,
passed=(actual2 == expected2),
))
# Case 3: Structural pseudo-classes first, last, odd, even, empty
page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
<ul id="lst">
<li class="first:text-red-500 last:font-bold odd:bg-gray-100 even:bg-gray-200">Item 1</li>
<li class="first:text-red-500 last:font-bold odd:bg-gray-100 even:bg-gray-200">Item 2</li>
<li class="first:text-red-500 last:font-bold odd:bg-gray-100 even:bg-gray-200">Item 3</li>
<li class="first:text-red-500 last:font-bold odd:bg-gray-100 even:bg-gray-200">Item 4</li>
</ul>
<div id="emp" class="empty:bg-gray-50"></div>
</body></html>""")
actual3 = page.evaluate("""() => {
const items = [...document.querySelectorAll('#lst li')].map(li => {
const s = getComputedStyle(li);
return { color: s.color, weight: s.fontWeight, bg: s.backgroundColor };
});
return {
firstColor: items[0].color,
lastWeight: items[3].weight,
oddBgs: [items[0].bg, items[2].bg],
evenBgs: [items[1].bg, items[3].bg],
emptyBg: getComputedStyle(document.getElementById('emp')).backgroundColor,
};
}""")
expected3 = {
"firstColor": "rgb(239, 68, 68)",
"lastWeight": "700",
"oddBgs": ["rgb(243, 244, 246)", "rgb(243, 244, 246)"],
"evenBgs": ["rgb(229, 231, 235)", "rgb(229, 231, 235)"],
"emptyBg": "rgb(249, 250, 251)",
}
cases.append(dict(
name="structural_pseudo_first_last_odd_even",
expected=expected3,
actual=actual3,
passed=(actual3 == expected3),
))
# Case 4: Form states (required, invalid, disabled, enabled, checked) & group-hover
page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
<input id="req" class="border p-2 required:border-red-500 invalid:border-yellow-500" type="email" value="not-an-email" required />
<input id="req-ok" class="border p-2 required:border-red-500 invalid:border-yellow-500" type="email" value="a@b.com" required />
<input id="dis" class="border p-2 disabled:bg-gray-300 disabled:opacity-50" type="text" disabled />
<input id="en" class="border p-2 enabled:border-blue-500" type="text" />
<input id="chk" class="checked:bg-blue-500" type="checkbox" checked />
<div id="grp" class="group" style="padding:20px; width:260px;">
<button id="grp-btn" class="px-4 py-2 bg-blue-500 text-white group-hover:bg-gray-300">Child</button>
</div>
</body></html>""")
before_grp = page.eval_on_selector("#grp-btn", "el => getComputedStyle(el).backgroundColor")
gbox = page.locator("#grp").bounding_box()
page.mouse.move(gbox["x"] + 5, gbox["y"] + 5)
after_grp = page.eval_on_selector("#grp-btn", "el => getComputedStyle(el).backgroundColor")
actual4 = page.evaluate("""(grp) => ({
invalidBorder: getComputedStyle(document.getElementById('req')).borderTopColor,
validRequiredBorder: getComputedStyle(document.getElementById('req-ok')).borderTopColor,
disabledBg: getComputedStyle(document.getElementById('dis')).backgroundColor,
disabledOpacity: getComputedStyle(document.getElementById('dis')).opacity,
enabledBorder: getComputedStyle(document.getElementById('en')).borderTopColor,
checkedMatches: document.getElementById('chk').matches(':checked'),
groupBeforeBg: grp.before,
groupHoverBg: grp.after,
})""", {"before": before_grp, "after": after_grp})
expected4 = {
"invalidBorder": "rgb(234, 179, 8)",
"validRequiredBorder": "rgb(239, 68, 68)",
"disabledBg": "rgb(209, 213, 219)",
"disabledOpacity": "0.5",
"enabledBorder": "rgb(59, 130, 246)",
"checkedMatches": True,
"groupBeforeBg": "rgb(59, 130, 246)",
"groupHoverBg": "rgb(209, 213, 219)",
}
cases.append(dict(
name="form_and_group_states",
expected=expected4,
actual=actual4,
passed=(actual4 == expected4),
))
# Case 5: Pseudo-elements (before/after), rtl, aria-checked, :target, motion-safe
page.emulate_media(reduced_motion="no-preference")
page.set_content(f"""<!doctype html>
<html><head><meta charset="utf-8"><style>{TW_CSS}</style></head>
<body>
<div id="pe" class="before:content-star after:content-bang">Label</div>
<div id="rtl" dir="rtl" class="rtl:text-right">RTL</div>
<div id="aria" aria-checked="true" class="aria-checked:bg-green-500">ARIA</div>
<div id="sec" class="target:bg-yellow-500">Target</div>
<div id="mot" class="motion-safe:duration-500">Motion</div>
</body></html>""")
page.evaluate("location.hash = '#sec'")
dur_safe = page.eval_on_selector("#mot", "el => getComputedStyle(el).transitionDuration")
page.emulate_media(reduced_motion="reduce")
dur_reduced = page.eval_on_selector("#mot", "el => getComputedStyle(el).transitionDuration")
actual5 = page.evaluate("""(m) => ({
beforeContent: getComputedStyle(document.getElementById('pe'), '::before').content,
afterContent: getComputedStyle(document.getElementById('pe'), '::after').content,
rtlAlign: getComputedStyle(document.getElementById('rtl')).textAlign,
ariaBg: getComputedStyle(document.getElementById('aria')).backgroundColor,
targetBg: getComputedStyle(document.getElementById('sec')).backgroundColor,
motionSafeDuration: m.safe,
motionReduceDuration: m.reduced,
})""", {"safe": dur_safe, "reduced": dur_reduced})
expected5 = {
"beforeContent": '"*"',
"afterContent": '"!"',
"rtlAlign": "right",
"ariaBg": "rgb(34, 197, 94)",
"targetBg": "rgb(234, 179, 8)",
"motionSafeDuration": "0.5s",
"motionReduceDuration": "0s",
}
cases.append(dict(
name="pseudo_elements_dir_aria_motion",
expected=expected5,
actual=actual5,
passed=(actual5 == expected5),
))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
run()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`odd:` 编译为 `:nth-child(odd)`,按 1 起始序号仅匹配第 1、3、5 项,第 2 项属于偶数位不会命中;正确做法是在所有 `<li>` 上统一添加 `odd:bg-gray-100 even:bg-gray-200`。