Bootstrap5 表格
核对 Bootstrap 5 基于 CSS 变量的表格样式体系:基础/条纹/带边框/无边框/悬停/深色组合、9 类上下文行色、表头配色、紧凑表格 .table-sm 及响应式横向滚动断点。
学完这一章,你能够
- 核对 Bootstrap 5 基于 CSS 变量的表格样式体系:基础/条纹/带边框/无边框/悬停/深色组合、9 类上下文行色、表头配色、紧凑表格 .table-sm 及响应式横向滚动断点。
基础表格、条纹、边框与无边框样式
Bootstrap 5 为原生 HTML `<table>` 提供了模块化的样式修饰类(排序与分页需结合自定义脚本或数据表格插件,原生 CSS 专注结构与响应式呈现)。只需为 `<table>` 添加 `.table` 即可获得 100% 宽度、合并边框、底部水平分隔线及规范单元格内边距;底层通过 `--bs-table-bg` 与 `box-shadow: inset 0 0 0 9999px var(--bs-table-accent-bg)` 叠加条纹与悬停色,避免覆盖行背景。
在此基础上可叠加边框与条纹类:`.table-striped` 为 `<tbody>` 奇数行添加斑马纹背景;`.table-bordered` 为表格四周及所有单元格补齐 1px 边框;`.table-borderless` 则移除单元格底边框呈现极简样式。本站离线实测:`.table` 呈 `border-collapse: collapse`、单元格内边距 `8px × 8px`、底边 `1px`;`.table-striped` 奇数行与偶数行内阴影着重色明显区分;`.table-bordered` 左侧边框 `1px`;`.table-borderless` 底边归零为 `0px`。
鼠标悬停与深色表格组合
`.table-hover` 在鼠标移过 `<tbody>` 任意行时高亮该行;`.table-dark` 将整表切换为深灰黑底(`rgb(33, 37, 41)`)配白字(`rgb(255, 255, 255)`);两者可自由叠加以构建 `.table-dark.table-striped`(深色条纹表)或 `.table-dark.table-hover`(深色悬停表)。本站通过 Playwright 真实触发行悬停,验证浅色悬停表与深色悬停表在 `:hover` 时 `--bs-table-accent-bg` 渲染阴影均实时切换。
上下文行颜色、表头颜色与紧凑表格
Bootstrap 5 提供 9 个语义颜色类用于高亮特定 `<tr>` 或 `<td>`(如 `.table-primary` 蓝底、`.table-success` 绿底、`.table-danger` 红底、`.table-warning` 黄底等;若对浅色背景表某行使用 `.table-dark` 时注意文字对比度,避免叠加 `.text-dark` 导致黑底黑字)。本站离线实测全部 9 类单元格背景与着重阴影色值均准确生效。
表头着色方面,Bootstrap 5 统一改用 `<thead class="table-dark">` 与 `<thead class="table-light">`(取代 Bootstrap 4 的 `.thead-dark` / `.thead-light`),本站实测两者表头单元格背景分别为 `rgb(33, 37, 41)` 与 `rgb(248, 249, 250)`。需要展示高密度数据时,添加 `.table-sm` 可将单元格内边距减半,实测由常规 `8px × 8px`(`0.5rem`)缩减为 `4px × 4px`(`0.25rem`)。
响应式表格与按断点横向滚动
列数较多时,可将 `<table>` 包裹在 `.table-responsive` 容器中以避免撑破页面宽度。需要辨析的是:官方 Bootstrap 5 中 `.table-responsive` 在任意视口下均设置 `overflow-x: auto`(只要内容宽于容器即出现横向滚动条),而仅在低于特定断点(如 `<992px`)才启用滚动条需使用带断点后缀的 `.table-responsive-lg` 等 5 个类(`sm/md/lg/xl/xxl`)。本站用 11 列宽表跨 6 档视口实测:`.table-responsive` 始终 `overflow-x: auto`(在 `500px`–`1300px` 触发横向滚动、`1450px` 空间充足时不溢出),而 `.table-responsive-sm/md/lg/xl/xxl` 精准在各自阈值之上切回 `visible`。
Bootstrap 5 表格语义颜色类对照表
| 类名 | 语义与视觉说明 | 实测单元格背景 / 特征 |
|---|---|---|
| .table-primary | 蓝色:标识重要操作或主状态 | rgb(207, 226, 255) |
| .table-success | 绿色:标识成功或允许执行的状态 | rgb(209, 231, 221) |
| .table-danger | 红色:标识错误或高风险操作 | rgb(248, 215, 218) |
| .table-info | 浅蓝色:标识提示或内容变更信息 | rgb(207, 244, 252) |
| .table-warning | 暖黄色:标识需重点关注的警告项 | rgb(255, 243, 205) |
| .table-active | 半透明灰:呈现当前激活或悬停高亮态 | 内阴影叠加 10% 透明黑层 |
| .table-secondary | 中性灰:标识次要辅助数据行 | rgb(226, 227, 229) |
| .table-light | 浅灰白:适用于柔和浅色表头或行背景 | rgb(248, 249, 250) |
| .table-dark | 深炭灰:适用于深色表头、行或整表背景 | rgb(33, 37, 41) 配白色文字 |
Bootstrap 5 响应式表格断点类对照表
| 响应式容器类 | 生效屏幕宽度阈值 | 实测 overflow-x 切换行为 |
|---|---|---|
| .table-responsive-sm | < 576px | 500px 为 auto,700px 起为 visible |
| .table-responsive-md | < 768px | 700px 为 auto,900px 起为 visible |
| .table-responsive-lg | < 992px | 900px 为 auto,1100px 起为 visible |
| .table-responsive-xl | < 1200px | 1100px 为 auto,1300px 起为 visible |
| .table-responsive-xxl | < 1400px | 1300px 为 auto,1450px 起为 visible |
离线 Chromium 实测 Bootstrap 5 表格变量体系、真实悬停高亮、9 类语义行色与 6 档响应式滚动
"""Offline Playwright Chromium lab for Bootstrap 5 Chapter 07 (tables)."""
import json
from playwright.sync_api import sync_playwright
BS5_CSS = """
*, *::before, *::after { box-sizing: border-box; }
html { font-size: 16px; }
body { margin: 0; font-family: system-ui, sans-serif; color: #212529; }
.table {
--bs-table-bg: transparent;
--bs-table-accent-bg: transparent;
--bs-table-striped-color: #212529;
--bs-table-striped-bg: rgba(0, 0, 0, 0.05);
--bs-table-active-color: #212529;
--bs-table-active-bg: rgba(0, 0, 0, 0.1);
--bs-table-hover-color: #212529;
--bs-table-hover-bg: rgba(0, 0, 0, 0.075);
width: 100%;
margin-bottom: 1rem;
color: #212529;
vertical-align: top;
border-color: #dee2e6;
border-collapse: collapse;
}
.table > :not(caption) > * > * {
padding: 0.5rem 0.5rem;
background-color: var(--bs-table-bg);
border-bottom: 1px solid var(--bs-table-border-color, #dee2e6);
box-shadow: inset 0 0 0 9999px var(--bs-table-accent-bg);
}
.table-sm > :not(caption) > * > * { padding: 0.25rem 0.25rem; }
.table-bordered > :not(caption) > * { border-width: 1px 0; border-style: solid; border-color: #dee2e6; }
.table-bordered > :not(caption) > * > * { border-width: 1px; border-style: solid; border-color: #dee2e6; }
.table-borderless > :not(caption) > * > * { border-bottom-width: 0; }
.table-striped > tbody > tr:nth-of-type(odd) > * { --bs-table-accent-bg: var(--bs-table-striped-bg); color: var(--bs-table-striped-color); }
.table-hover > tbody > tr:hover > * { --bs-table-accent-bg: var(--bs-table-hover-bg); color: var(--bs-table-hover-color); }
.table-primary { --bs-table-bg: #cfe2ff; --bs-table-border-color: #bacbe6; color: #000; }
.table-secondary { --bs-table-bg: #e2e3e5; --bs-table-border-color: #cbccce; color: #000; }
.table-success { --bs-table-bg: #d1e7dd; --bs-table-border-color: #bcd0c7; color: #000; }
.table-info { --bs-table-bg: #cff4fc; --bs-table-border-color: #badce3; color: #000; }
.table-warning { --bs-table-bg: #fff3cd; --bs-table-border-color: #e6dbb9; color: #000; }
.table-danger { --bs-table-bg: #f8d7da; --bs-table-border-color: #dfc2c4; color: #000; }
.table-light { --bs-table-bg: #f8f9fa; --bs-table-border-color: #dfe0e1; color: #000; }
.table-active { --bs-table-accent-bg: var(--bs-table-active-bg); color: var(--bs-table-active-color); }
.table-dark {
--bs-table-bg: #212529;
--bs-table-striped-bg: #2c3034;
--bs-table-striped-color: #fff;
--bs-table-hover-bg: #323539;
--bs-table-hover-color: #fff;
--bs-table-border-color: #373b3e;
color: #fff;
border-color: #373b3e;
}
.table-responsive { overflow-x: auto; }
@media (max-width: 575.98px) { .table-responsive-sm { overflow-x: auto; } }
@media (max-width: 767.98px) { .table-responsive-md { overflow-x: auto; } }
@media (max-width: 991.98px) { .table-responsive-lg { overflow-x: auto; } }
@media (max-width: 1199.98px) { .table-responsive-xl { overflow-x: auto; } }
@media (max-width: 1399.98px) { .table-responsive-xxl { overflow-x: auto; } }
"""
WIDE_COLS = "".join(f"<th style='min-width:120px'>Col{i}</th>" for i in range(1, 12))
WIDE_TDS = "".join("<td>Val</td>" for _ in range(1, 12))
HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{BS5_CSS}</style></head>
<body>
<table id="t-basic" class="table"><tbody><tr><td>A</td></tr><tr><td>B</td></tr></tbody></table>
<table id="t-striped" class="table table-striped"><tbody><tr><td id="st-odd">Odd</td></tr><tr><td id="st-even">Even</td></tr></tbody></table>
<table id="t-bordered" class="table table-bordered"><tbody><tr><td id="bd-td">Bordered</td></tr></tbody></table>
<table id="t-borderless" class="table table-borderless"><tbody><tr><td id="bl-td">Borderless</td></tr></tbody></table>
<table id="t-hover" class="table table-hover"><tbody><tr id="hv-row"><td id="hv-td">HoverLight</td></tr></tbody></table>
<table id="t-dark-hover" class="table table-dark table-striped table-hover"><tbody><tr id="dhv-row"><td id="dhv-td">DarkRow1</td></tr><tr><td id="dhv-td2">DarkRow2</td></tr></tbody></table>
<table id="t-ctx" class="table">
<thead id="th-dark" class="table-dark"><tr><th id="th-dark-cell">HeadDark</th></tr></thead>
<tbody>
<tr class="table-primary"><td data-k="primary">P</td></tr>
<tr class="table-success"><td data-k="success">S</td></tr>
<tr class="table-danger"><td data-k="danger">D</td></tr>
<tr class="table-info"><td data-k="info">I</td></tr>
<tr class="table-warning"><td data-k="warning">W</td></tr>
<tr class="table-active"><td data-k="active">A</td></tr>
<tr class="table-secondary"><td data-k="secondary">Sec</td></tr>
<tr class="table-light"><td data-k="light">L</td></tr>
<tr class="table-dark"><td data-k="dark">Dk</td></tr>
</tbody>
</table>
<table class="table"><thead class="table-light"><tr><th id="th-light-cell">HeadLight</th></tr></thead></table>
<table id="t-sm" class="table table-bordered table-sm"><tbody><tr><td id="sm-td">Compact</td></tr></tbody></table>
<div id="resp-all" class="table-responsive"><table class="table"><thead><tr>{WIDE_COLS}</tr></thead><tbody><tr>{WIDE_TDS}</tr></tbody></table></div>
<div id="resp-sm" class="table-responsive-sm"><table class="table"><thead><tr>{WIDE_COLS}</tr></thead></table></div>
<div id="resp-md" class="table-responsive-md"><table class="table"><thead><tr>{WIDE_COLS}</tr></thead></table></div>
<div id="resp-lg" class="table-responsive-lg"><table class="table"><thead><tr>{WIDE_COLS}</tr></thead></table></div>
<div id="resp-xl" class="table-responsive-xl"><table class="table"><thead><tr>{WIDE_COLS}</tr></thead></table></div>
<div id="resp-xxl" class="table-responsive-xxl"><table class="table"><thead><tr>{WIDE_COLS}</tr></thead></table></div>
</body>
</html>
"""
def launch_browser(pw):
try:
return pw.chromium.launch(headless=True)
except Exception:
return pw.chromium.launch(headless=True, channel="chrome")
def main():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 1000, "height": 900})
page.set_content(HTML_DOC)
# Case 1: basic, striped, bordered, borderless
c1 = page.evaluate("""() => {
const tb = getComputedStyle(document.getElementById('t-basic'));
const btd = getComputedStyle(document.querySelector('#t-basic td'));
const odd = getComputedStyle(document.getElementById('st-odd'));
const even = getComputedStyle(document.getElementById('st-even'));
const bd = getComputedStyle(document.getElementById('bd-td'));
const bl = getComputedStyle(document.getElementById('bl-td'));
return {
border_collapse: tb.borderCollapse,
basic_padding: [btd.paddingTop, btd.paddingLeft],
basic_bottom_border: btd.borderBottomWidth,
striped_odd_differs_from_even: odd.boxShadow !== even.boxShadow,
bordered_left_width: bd.borderLeftWidth,
borderless_bottom_width: bl.borderBottomWidth
};
}""")
exp1 = {
"border_collapse": "collapse",
"basic_padding": ["8px", "8px"],
"basic_bottom_border": "1px",
"striped_odd_differs_from_even": True,
"bordered_left_width": "1px",
"borderless_bottom_width": "0px",
}
cases.append({
"name": "basic_striped_bordered_borderless",
"passed": c1 == exp1,
"expected": exp1,
"actual": c1,
})
# Case 2: hover & dark combinations (with real Playwright hover)
hv_before = page.eval_on_selector("#hv-td", "el => getComputedStyle(el).boxShadow")
page.hover("#hv-row")
hv_after = page.eval_on_selector("#hv-td", "el => getComputedStyle(el).boxShadow")
dk_bg = page.eval_on_selector("#dhv-td2", "el => getComputedStyle(el).backgroundColor")
dk_color = page.eval_on_selector("#dhv-td2", "el => getComputedStyle(el).color")
dhv_before = page.eval_on_selector("#dhv-td2", "el => getComputedStyle(el).boxShadow")
page.hover("#dhv-td2")
dhv_after = page.eval_on_selector("#dhv-td2", "el => getComputedStyle(el).boxShadow")
c2 = {
"light_hover_changes_accent": hv_before != hv_after,
"dark_bg": dk_bg,
"dark_color": dk_color,
"dark_hover_changes_accent": dhv_before != dhv_after,
}
exp2 = {
"light_hover_changes_accent": True,
"dark_bg": "rgb(33, 37, 41)",
"dark_color": "rgb(255, 255, 255)",
"dark_hover_changes_accent": True,
}
cases.append({
"name": "hover_and_dark_combinations",
"passed": c2 == exp2,
"expected": exp2,
"actual": c2,
})
# Case 3: contextual row colors & thead-dark / thead-light (BS5 .table-dark / .table-light)
c3 = page.evaluate("""() => {
const rows = {};
for (const td of document.querySelectorAll('#t-ctx tbody td')) {
const cs = getComputedStyle(td);
rows[td.dataset.k] = td.dataset.k === 'active' ? cs.boxShadow.includes('0.1') : cs.backgroundColor;
}
return {
rows,
thead_dark_bg: getComputedStyle(document.getElementById('th-dark-cell')).backgroundColor,
thead_light_bg: getComputedStyle(document.getElementById('th-light-cell')).backgroundColor
};
}""")
exp3 = {
"rows": {
"primary": "rgb(207, 226, 255)",
"success": "rgb(209, 231, 221)",
"danger": "rgb(248, 215, 218)",
"info": "rgb(207, 244, 252)",
"warning": "rgb(255, 243, 205)",
"active": True,
"secondary": "rgb(226, 227, 229)",
"light": "rgb(248, 249, 250)",
"dark": "rgb(33, 37, 41)",
},
"thead_dark_bg": "rgb(33, 37, 41)",
"thead_light_bg": "rgb(248, 249, 250)",
}
cases.append({
"name": "contextual_row_and_thead_colors",
"passed": c3 == exp3,
"expected": exp3,
"actual": c3,
})
# Case 4: compact .table-sm padding
c4 = page.evaluate("""() => {
const norm = getComputedStyle(document.querySelector('#t-basic td'));
const sm = getComputedStyle(document.getElementById('sm-td'));
return {
normal_padding: [norm.paddingTop, norm.paddingLeft],
sm_padding: [sm.paddingTop, sm.paddingLeft]
};
}""")
exp4 = {
"normal_padding": ["8px", "8px"],
"sm_padding": ["4px", "4px"],
}
cases.append({
"name": "compact_table_sm",
"passed": c4 == exp4,
"expected": exp4,
"actual": c4,
})
# Case 5: responsive table breakpoints
resp_check = {}
for vw in (500, 700, 900, 1100, 1300, 1450):
page.set_viewport_size({"width": vw, "height": 900})
resp_check[str(vw)] = page.evaluate("""() => {
const pick = id => getComputedStyle(document.getElementById(id)).overflowX;
const ra = document.getElementById('resp-all');
return {
all: pick('resp-all'),
all_scrolls: ra.scrollWidth > ra.clientWidth,
sm: pick('resp-sm'),
md: pick('resp-md'),
lg: pick('resp-lg'),
xl: pick('resp-xl'),
xxl: pick('resp-xxl')
};
}""")
exp5 = {
"500": {"all": "auto", "all_scrolls": True, "sm": "auto", "md": "auto", "lg": "auto", "xl": "auto", "xxl": "auto"},
"700": {"all": "auto", "all_scrolls": True, "sm": "visible", "md": "auto", "lg": "auto", "xl": "auto", "xxl": "auto"},
"900": {"all": "auto", "all_scrolls": True, "sm": "visible", "md": "visible", "lg": "auto", "xl": "auto", "xxl": "auto"},
"1100": {"all": "auto", "all_scrolls": True, "sm": "visible", "md": "visible", "lg": "visible", "xl": "auto", "xxl": "auto"},
"1300": {"all": "auto", "all_scrolls": True, "sm": "visible", "md": "visible", "lg": "visible", "xl": "visible", "xxl": "auto"},
"1450": {"all": "auto", "all_scrolls": False, "sm": "visible", "md": "visible", "lg": "visible", "xl": "visible", "xxl": "visible"},
}
cases.append({
"name": "responsive_table_breakpoints",
"passed": resp_check == exp5,
"expected": exp5,
"actual": resp_check,
})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对基础/条纹/边框/无边框、浅深色行悬停、9 类语义色与表头色、.table-sm 4px 内边距及 .table-responsive* 断点切换。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:11085b875cc87810c6af6a11a2349c0c93b64a9a43eac3870d451d444c8aee5b
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:e1316409253b70ea1183d546d17e866464b016240680557515910bac85fc911e
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
Bootstrap 5 中如何为 <thead> 单独设置深色表头?.table-responsive 与 .table-responsive-lg 在触发条件上有何差异?
展开参考解答
Bootstrap 5 直接在 <thead> 上添加 .table-dark(或 .table-light),不再使用 Bootstrap 4 的 .thead-dark;.table-responsive 在任何屏幕宽度下都保持 overflow-x: auto,只要表格宽于容器即可横向滚动,而 .table-responsive-lg 仅在视口小于 992px 时启用 overflow-x: auto。