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

Bootstrap4 表格

核对 Bootstrap 4 基础表格、条纹/边框/悬停/深色/无边框组合变体、9 项语义行色类、表头主题与旧版类迁移、紧凑表格及全断点响应式横向滚动表格实测。

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

学完这一章,你能够

基础表格、条纹、边框与无边框样式

为 `<table>` 添加 `.table` 基类即可启用 Bootstrap 4 默认表格样式:宽 `100%`、合并边框,单元格默认四周内边距 `0.75rem`(实测 `12px`)并带 `1px solid #dee2e6` 顶部分隔线。

在此基础上可自由组合外观修饰类:`.table-striped` 通过 `tbody tr:nth-of-type(odd)` 为奇数行叠加 `rgba(0, 0, 0, 0.05)` 浅灰条纹(偶数行保持透明);`.table-bordered` 为表格外框与所有单元格补齐四侧 `1px solid` 边框;`.table-borderless` 则彻底移除表头与表体的所有边框(实测 `border-top-width: 0px`)。

悬停高亮与深色背景组合

`.table-hover` 在鼠标悬停于表体行时呈现浅灰反馈(Playwright 真实 `.hover()` 实测背景为 `rgba(0, 0, 0, 0.075)`)。`.table-dark` 将整张表格切换为深灰底 `rgb(52, 58, 64)` 配白字 `rgb(255, 255, 255)`,还可分别与 `.table-striped`(奇数行叠加 `rgba(255, 255, 255, 0.05)` 亮色条纹)及 `.table-hover`(悬停叠加 `rgba(255, 255, 255, 0.075)` 高亮)联合使用。

语义状态颜色类与表头/紧凑变体

Bootstrap 4 为 `<tr>` 行或 `<td>`/`<th>` 单元格提供了 9 组语义背景类(`.table-primary` 至 `.table-dark` 及 `.table-active`),便于直观标识重要、成功、危险、变更或次要数据记录,详见下方速查表。

若只想单独突出表头,可在 `<thead>` 上使用 `.thead-dark`(实测深底 `rgb(52, 58, 64)`、白字)或 `.thead-light`(实测浅灰底 `rgb(233, 236, 239)`、深灰字 `rgb(73, 80, 87)`);注意在早期 `v4.0.0-beta` 中它们曾命名为 `.thead-inverse` 与 `.thead-default`,自 `v4.0.0-beta.2` 起已统一更名并沿用至正式版。需要高密度信息排版时,添加 `.table-sm` 会将单元格内边距由 `12px` 压缩至 `0.3rem`(`4.8px`),整表高度显著减小。

响应式水平滚动表格

面对多列宽表,用 `<div class="table-responsive">` 包裹 `<table>` 可启用横向溢出滚动(`overflow-x: auto`),确保窄屏下不会撑破页面外框,而在宽屏内容未溢出时不会出现多余滚动条(早期说明常以 `992px` 为参考描述宽窄屏切换)。若需只在指定断点以下才启用横向滚动,可使用 `.table-responsive-sm/md/lg/xl`。本站在 `500px`、`700px`、`900px`、`1100px`、`1300px` 五档视口实测 11 列宽表:`.table-responsive-sm` 仅在 `500px`(`<576px`)保持 `overflow-x: auto`,到 `700px` 起回退为 `visible`;其余 `-md`/`-lg`/`-xl` 亦严格在各自阈值下切换,且 `1300px` 时所有容器均不再横向溢出(`scrollWidth <= clientWidth`)。

Bootstrap 4 表格语义行/单元格颜色类

类名状态含义离线实测背景色
.table-primary蓝色:标识重要操作或核心数据行rgb(184, 218, 255)
.table-success绿色:标识成功或允许执行的状态rgb(195, 230, 203)
.table-danger红色:标识危险、告警或失败记录rgb(245, 198, 203)
.table-info浅蓝色:标识信息变更或中性提示rgb(190, 229, 235)
.table-warning暖黄色:标识需要留意或待处理项rgb(255, 238, 186)
.table-active浅灰半透明:模拟行激活或悬停底色rgba(0, 0, 0, 0.075)
.table-secondary灰色:标识次要或较低优先级内容rgb(214, 216, 219)
.table-light极浅灰:浅色表格行背景rgb(253, 253, 254)
.table-dark较深灰:深色行背景(常搭配深色/浅色文字调整对比度)rgb(198, 200, 202)

按断点生效的响应式表格类

类名启用水平滚动的屏幕宽度条件跨视口切换实测
.table-responsive-sm< 576px500px 时 overflow-x: auto,700px 起为 visible
.table-responsive-md< 768px700px 时 overflow-x: auto,900px 起为 visible
.table-responsive-lg< 992px900px 时 overflow-x: auto,1100px 起为 visible
.table-responsive-xl< 1200px1100px 时 overflow-x: auto,1300px 起为 visible

离线验证 Bootstrap 4 表格变体、悬停/深色组合、语义行色与断点响应式滚动

python · 阅读源码
"""Offline Playwright Chromium lab for Bootstrap 4 Ch 06 (tables)."""
import json
from playwright.sync_api import sync_playwright

BS4_TABLE_CSS = """
*, *::before, *::after { box-sizing: border-box; }
body { margin: 0; font-family: sans-serif; font-size: 16px; color: #212529; background: #fff; }
table { border-collapse: collapse; }
.table { width: 100%; margin-bottom: 1rem; color: #212529; }
.table th, .table td { padding: 0.75rem; vertical-align: top; border-top: 1px solid #dee2e6; }
.table thead th { vertical-align: bottom; border-bottom: 2px solid #dee2e6; }
.table-sm th, .table-sm td { padding: 0.3rem; }
.table-bordered { border: 1px solid #dee2e6; }
.table-bordered th, .table-bordered td { border: 1px solid #dee2e6; }
.table-borderless th, .table-borderless td, .table-borderless thead th, .table-borderless tbody + tbody { border: 0; }
.table-striped tbody tr:nth-of-type(odd) { background-color: rgba(0, 0, 0, 0.05); }
.table-hover tbody tr:hover { color: #212529; background-color: rgba(0, 0, 0, 0.075); }
.table-primary, .table-primary > th, .table-primary > td { background-color: #b8daff; }
.table-secondary, .table-secondary > th, .table-secondary > td { background-color: #d6d8db; }
.table-success, .table-success > th, .table-success > td { background-color: #c3e6cb; }
.table-info, .table-info > th, .table-info > td { background-color: #bee5eb; }
.table-warning, .table-warning > th, .table-warning > td { background-color: #ffeeba; }
.table-danger, .table-danger > th, .table-danger > td { background-color: #f5c6cb; }
.table-light, .table-light > th, .table-light > td { background-color: #fdfdfe; }
.table-dark, .table-dark > th, .table-dark > td { background-color: #c6c8ca; }
.table-active, .table-active > th, .table-active > td { background-color: rgba(0, 0, 0, 0.075); }
.table .thead-dark th { color: #fff; background-color: #343a40; border-color: #454d55; }
.table .thead-light th { color: #495057; background-color: #e9ecef; border-color: #dee2e6; }
table.table-dark { color: #fff; background-color: #343a40; }
table.table-dark th, table.table-dark td, table.table-dark thead th { border-color: #454d55; }
table.table-dark.table-striped tbody tr:nth-of-type(odd) { background-color: rgba(255, 255, 255, 0.05); }
table.table-dark.table-hover tbody tr:hover { color: #fff; background-color: rgba(255, 255, 255, 0.075); }
.table-responsive { display: block; width: 100%; overflow-x: auto; }
@media (max-width: 575.98px) { .table-responsive-sm { display: block; width: 100%; overflow-x: auto; } }
@media (max-width: 767.98px) { .table-responsive-md { display: block; width: 100%; overflow-x: auto; } }
@media (max-width: 991.98px) { .table-responsive-lg { display: block; width: 100%; overflow-x: auto; } }
@media (max-width: 1199.98px) { .table-responsive-xl { display: block; width: 100%; overflow-x: auto; } }
.wide-table th, .wide-table td { white-space: nowrap; min-width: 110px; }
"""

ROWS_3 = """
<thead><tr><th>Firstname</th><th>Lastname</th><th>Email</th></tr></thead>
<tbody>
  <tr><td>John</td><td>Doe</td><td>john@example.com</td></tr>
  <tr><td>Mary</td><td>Moe</td><td>mary@example.com</td></tr>
  <tr><td>July</td><td>Dooley</td><td>july@example.com</td></tr>
</tbody>
"""

WIDE_COLS = "".join(f"<th>Col{i}</th>" for i in range(1, 12))
WIDE_VALS = "".join(f"<td>Value{i}</td>" for i in range(1, 12))
WIDE_HTML = f'<table class="table wide-table"><thead><tr>{WIDE_COLS}</tr></thead><tbody><tr>{WIDE_VALS}</tr></tbody></table>'

HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{BS4_TABLE_CSS}</style></head>
<body>
  <table id="t-basic" class="table">{ROWS_3}</table>
  <table id="t-striped" class="table table-striped">{ROWS_3}</table>
  <table id="t-bordered" class="table table-bordered">{ROWS_3}</table>
  <table id="t-borderless" class="table table-borderless">{ROWS_3}</table>
  <table id="t-hover" class="table table-hover">{ROWS_3}</table>
  <table id="t-dark" class="table table-dark">{ROWS_3}</table>
  <table id="t-dark-striped" class="table table-dark table-striped">{ROWS_3}</table>
  <table id="t-dark-hover" class="table table-dark table-hover">{ROWS_3}</table>
  <table id="t-ctx" class="table">
    <tbody>
      <tr class="table-primary"><td>primary</td></tr>
      <tr class="table-success"><td>success</td></tr>
      <tr class="table-danger"><td>danger</td></tr>
      <tr class="table-info"><td>info</td></tr>
      <tr class="table-warning"><td>warning</td></tr>
      <tr class="table-active"><td>active</td></tr>
      <tr class="table-secondary"><td>secondary</td></tr>
      <tr class="table-light"><td>light</td></tr>
      <tr class="table-dark"><td>dark</td></tr>
    </tbody>
  </table>
  <table id="t-head-dark" class="table"><thead class="thead-dark"><tr><th>A</th></tr></thead><tbody><tr><td>1</td></tr></tbody></table>
  <table id="t-head-light" class="table"><thead class="thead-light"><tr><th>A</th></tr></thead><tbody><tr><td>1</td></tr></tbody></table>
  <table id="t-sm" class="table table-bordered table-sm">{ROWS_3}</table>
  <div id="r-all" class="table-responsive">{WIDE_HTML}</div>
  <div id="r-sm" class="table-responsive-sm">{WIDE_HTML}</div>
  <div id="r-md" class="table-responsive-md">{WIDE_HTML}</div>
  <div id="r-lg" class="table-responsive-lg">{WIDE_HTML}</div>
  <div id="r-xl" class="table-responsive-xl">{WIDE_HTML}</div>
</body>
</html>
"""


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": 1000, "height": 900})
        page.set_content(HTML_PAGE)

        # Case 1: basic_striped_bordered_borderless
        res1 = page.evaluate("""() => {
            const bTd = getComputedStyle(document.querySelector('#t-basic tbody td'));
            const sOdd = getComputedStyle(document.querySelector('#t-striped tbody tr:nth-child(1)'));
            const sEven = getComputedStyle(document.querySelector('#t-striped tbody tr:nth-child(2)'));
            const bdTd = getComputedStyle(document.querySelector('#t-bordered tbody td'));
            const blTd = getComputedStyle(document.querySelector('#t-borderless tbody td'));
            return {
                basic_td_padding: bTd.paddingTop,
                basic_td_border_top: bTd.borderTopWidth + ' ' + bTd.borderTopStyle,
                striped_odd_bg: sOdd.backgroundColor,
                striped_even_bg: sEven.backgroundColor,
                bordered_left_border: bdTd.borderLeftWidth + ' ' + bdTd.borderLeftStyle,
                borderless_top_border: blTd.borderTopWidth,
            };
        }""")
        expected_1 = {
            "basic_td_padding": "12px",
            "basic_td_border_top": "1px solid",
            "striped_odd_bg": "rgba(0, 0, 0, 0.05)",
            "striped_even_bg": "rgba(0, 0, 0, 0)",
            "bordered_left_border": "1px solid",
            "borderless_top_border": "0px",
        }
        cases.append(dict(name="basic_striped_bordered_borderless", passed=(res1 == expected_1), expected=expected_1, actual=res1))

        # Case 2: hover_and_dark_table_variants
        page.locator("#t-hover tbody tr").first.hover()
        light_hover = page.evaluate("() => getComputedStyle(document.querySelector('#t-hover tbody tr')).backgroundColor")
        page.locator("#t-dark-hover tbody tr").first.hover()
        dark_hover = page.evaluate("() => getComputedStyle(document.querySelector('#t-dark-hover tbody tr')).backgroundColor")
        dark_base = page.evaluate("""() => {
            const d = getComputedStyle(document.getElementById('t-dark'));
            const ds = getComputedStyle(document.querySelector('#t-dark-striped tbody tr:nth-child(1)'));
            return { bg: d.backgroundColor, color: d.color, dark_striped_odd: ds.backgroundColor };
        }""")
        actual_2 = {
            "light_hover_bg": light_hover,
            "dark_bg": dark_base["bg"],
            "dark_color": dark_base["color"],
            "dark_striped_odd_bg": dark_base["dark_striped_odd"],
            "dark_hover_bg": dark_hover,
        }
        expected_2 = {
            "light_hover_bg": "rgba(0, 0, 0, 0.075)",
            "dark_bg": "rgb(52, 58, 64)",
            "dark_color": "rgb(255, 255, 255)",
            "dark_striped_odd_bg": "rgba(255, 255, 255, 0.05)",
            "dark_hover_bg": "rgba(255, 255, 255, 0.075)",
        }
        cases.append(dict(name="hover_and_dark_table_variants", passed=(actual_2 == expected_2), expected=expected_2, actual=actual_2))

        # Case 3: contextual_row_colors
        ctx = page.evaluate("""() => {
            const out = {};
            for (const tr of document.querySelectorAll('#t-ctx tbody tr')) {
                out[tr.className] = getComputedStyle(tr).backgroundColor;
            }
            return out;
        }""")
        expected_3 = {
            "table-primary": "rgb(184, 218, 255)",
            "table-success": "rgb(195, 230, 203)",
            "table-danger": "rgb(245, 198, 203)",
            "table-info": "rgb(190, 229, 235)",
            "table-warning": "rgb(255, 238, 186)",
            "table-active": "rgba(0, 0, 0, 0.075)",
            "table-secondary": "rgb(214, 216, 219)",
            "table-light": "rgb(253, 253, 254)",
            "table-dark": "rgb(198, 200, 202)",
        }
        cases.append(dict(name="contextual_row_colors", passed=(ctx == expected_3), expected=expected_3, actual=ctx))

        # Case 4: thead_colors_and_compact_sm
        res4 = page.evaluate("""() => {
            const hd = getComputedStyle(document.querySelector('#t-head-dark thead th'));
            const hl = getComputedStyle(document.querySelector('#t-head-light thead th'));
            const smTd = getComputedStyle(document.querySelector('#t-sm tbody td'));
            const hBasic = Math.round(document.getElementById('t-bordered').getBoundingClientRect().height);
            const hSm = Math.round(document.getElementById('t-sm').getBoundingClientRect().height);
            return {
                thead_dark: { bg: hd.backgroundColor, color: hd.color },
                thead_light: { bg: hl.backgroundColor, color: hl.color },
                sm_padding: smTd.paddingTop,
                sm_shorter_than_standard: hSm < hBasic,
            };
        }""")
        expected_4 = {
            "thead_dark": {"bg": "rgb(52, 58, 64)", "color": "rgb(255, 255, 255)"},
            "thead_light": {"bg": "rgb(233, 236, 239)", "color": "rgb(73, 80, 87)"},
            "sm_padding": "4.8px",
            "sm_shorter_than_standard": True,
        }
        cases.append(dict(name="thead_colors_and_compact_sm", passed=(res4 == expected_4), expected=expected_4, actual=res4))

        # Case 5: responsive_table_overflow
        resp = {}
        for vw in (500, 700, 900, 1100, 1300):
            page.set_viewport_size({"width": vw, "height": 900})
            resp[str(vw)] = page.evaluate("""() => {
                const check = id => {
                    const el = document.getElementById(id);
                    const s = getComputedStyle(el);
                    return { ox: s.overflowX, scrolls: el.scrollWidth > el.clientWidth };
                };
                return {
                    all: check('r-all'),
                    sm: check('r-sm'),
                    md: check('r-md'),
                    lg: check('r-lg'),
                    xl: check('r-xl'),
                };
            }""")
        expected_5 = {
            "500": {
                "all": {"ox": "auto", "scrolls": True},
                "sm": {"ox": "auto", "scrolls": True},
                "md": {"ox": "auto", "scrolls": True},
                "lg": {"ox": "auto", "scrolls": True},
                "xl": {"ox": "auto", "scrolls": True},
            },
            "700": {
                "all": {"ox": "auto", "scrolls": True},
                "sm": {"ox": "visible", "scrolls": True},
                "md": {"ox": "auto", "scrolls": True},
                "lg": {"ox": "auto", "scrolls": True},
                "xl": {"ox": "auto", "scrolls": True},
            },
            "900": {
                "all": {"ox": "auto", "scrolls": True},
                "sm": {"ox": "visible", "scrolls": True},
                "md": {"ox": "visible", "scrolls": True},
                "lg": {"ox": "auto", "scrolls": True},
                "xl": {"ox": "auto", "scrolls": True},
            },
            "1100": {
                "all": {"ox": "auto", "scrolls": True},
                "sm": {"ox": "visible", "scrolls": True},
                "md": {"ox": "visible", "scrolls": True},
                "lg": {"ox": "visible", "scrolls": True},
                "xl": {"ox": "auto", "scrolls": True},
            },
            "1300": {
                "all": {"ox": "auto", "scrolls": False},
                "sm": {"ox": "visible", "scrolls": False},
                "md": {"ox": "visible", "scrolls": False},
                "lg": {"ox": "visible", "scrolls": False},
                "xl": {"ox": "visible", "scrolls": False},
            },
        }
        cases.append(dict(name="responsive_table_overflow", passed=(resp == expected_5), expected=expected_5, actual=resp))

        browser.close()

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


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对基础/条纹/边框/无边框样式、浅深双主题悬停高亮、9 项语义行色 RGB、.thead-dark/.thead-light 与 .table-sm 4.8px 内边距,以及五档视口下的响应式滚动开关。
离线验证 Bootstrap 4 表格变体、悬停/深色组合、语义行色与断点响应式滚动

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

当前源码 SHA256:916f79c7028d1bcddedd652a7575c9a09acbb0ea6937eb42837b7fd58b163c4c

下载本站示例源码

本地运行

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

下载Bootstrap4 表格实验

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

ZIP SHA256:8cf6360c6fd11730aee383b8b80e4f20d75c20a3792bd0a489794f27fd0cf4f3

常见错误与边界

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

练习与解答

Bootstrap 4 正式版中设置深色与浅色表头应使用什么类名?.table-responsive-md 在 800px 视口下是否启用水平滚动容器?

展开参考解答

正式版应使用 .thead-dark 与 .thead-light(取代了早期 beta 版的 .thead-inverse 与 .thead-default);.table-responsive-md 仅在视口小于 768px 时启用 overflow-x: auto,因此在 800px 视口下不会启用滚动容器。

规范与官方依据