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

Bootstrap5 按钮组

核对 Bootstrap 5 水平/垂直按钮组、尺寸缩放、内嵌下拉菜单及多组并列显示的布局与交互。

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

学完这一章,你能够

基础水平按钮组与边框圆角合并

在 `<div>` 容器上添加 `.btn-group`(推荐附加 `role="group"`)可将多个按钮紧贴排列在同一水平行中。本站离线 Chromium 实测确认 `.btn-group` 采用 `display: inline-flex`,3 个按钮顶部坐标完全对齐,后续按钮通过 `margin-left: -1px` 消除双倍边框,相邻内侧圆角自动归零(`0px`),仅保留首尾外侧 `6px` 圆角。

无需逐个修改子按钮,只需在容器上叠加 `.btn-group-lg` 或 `.btn-group-sm` 即可整体缩放整组尺寸。实测 `.btn-group-lg` 内按钮字号为 `20px`、`.btn-group-sm` 为 `14px`,渲染高度呈 `lg > 默认 > sm` 递增。

垂直按钮组

将容器类替换为 `.btn-group-vertical` 后,主轴切换为 `flex-direction: column`,子按钮自上而下等宽堆叠并合并上下相邻边框。实测 3 个按钮垂直坐标严格递增且渲染宽度完全一致。

内嵌按钮组与下拉菜单

在 `.btn-group` 内再嵌套一个 `.btn-group` 包裹触发按钮(含 `.dropdown-toggle` 与 `data-bs-toggle="dropdown"`)及 `.dropdown-menu`,即可形成带下拉子菜单的复合按钮组。实测点击 `Sony` 触发按钮后,菜单由 `display: none` 切换为 `block`、`aria-expanded` 变为 `"true"` 并展示 `Tablet`/`Smartphone` 两项,再次点击恢复收起。

垂直按钮组 `.btn-group-vertical` 同样支持嵌套 `.btn-group` 下拉菜单(菜单容器可用 `<ul>` 或 `<div>`)。实测点击垂直组末端的 `Sony` 按钮同样准确触发展开与 `aria-expanded="true"` 同步。

多组并列显示

由于 `.btn-group` 为 `inline-flex` 行内弹性盒,在页面中连续书写多个 `.btn-group` 容器时它们会自然并排位于同一行(工具栏场景可进一步外包 `.btn-toolbar`)。实测两组按钮顶部对齐且第二组紧邻第一组右侧。

在离线 Chromium 中验证水平/垂直按钮组、尺寸缩放与内嵌下拉菜单

python · 阅读源码
"""Offline Playwright Chromium verification for Bootstrap 5 Button Groups (Ch 12)."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<style>
  *, *::before, *::after { box-sizing: border-box; }
  html { font-size: 16px; }
  body { margin: 16px; font-family: system-ui, -apple-system, "Segoe UI", sans-serif; line-height: 1.5; }
  .btn {
    display: inline-block; font-weight: 400; line-height: 1.5; text-align: center;
    cursor: pointer; border: 1px solid transparent; padding: 0.375rem 0.75rem;
    font-size: 1rem; border-radius: 0.375rem;
  }
  .btn-primary { color: #fff; background-color: #0d6efd; border-color: #0d6efd; }
  .btn-group, .btn-group-vertical { position: relative; display: inline-flex; vertical-align: middle; }
  .btn-group > .btn, .btn-group-vertical > .btn { position: relative; flex: 1 1 auto; }
  .btn-group > .btn:not(:first-child),
  .btn-group > .btn-group:not(:first-child) { margin-left: -1px; }
  .btn-group > .btn:not(:last-child):not(.dropdown-toggle),
  .btn-group > .btn-group:not(:last-child) > .btn {
    border-top-right-radius: 0; border-bottom-right-radius: 0;
  }
  .btn-group > .btn:nth-child(n+3),
  .btn-group > :not(.btn-check) + .btn,
  .btn-group > .btn-group:not(:first-child) > .btn {
    border-top-left-radius: 0; border-bottom-left-radius: 0;
  }
  .btn-group-lg > .btn { padding: 0.5rem 1rem; font-size: 1.25rem; border-radius: 0.5rem; }
  .btn-group-sm > .btn { padding: 0.25rem 0.5rem; font-size: 0.875rem; border-radius: 0.25rem; }
  .btn-group-vertical { flex-direction: column; align-items: flex-start; justify-content: center; }
  .btn-group-vertical > .btn, .btn-group-vertical > .btn-group { width: 100%; }
  .btn-group-vertical > .btn:not(:first-child),
  .btn-group-vertical > .btn-group:not(:first-child) { margin-top: -1px; }
  .btn-group-vertical > .btn:not(:last-child):not(.dropdown-toggle),
  .btn-group-vertical > .btn-group:not(:last-child) > .btn {
    border-bottom-right-radius: 0; border-bottom-left-radius: 0;
  }
  .btn-group-vertical > .btn ~ .btn,
  .btn-group-vertical > .btn-group:not(:first-child) > .btn {
    border-top-left-radius: 0; border-top-right-radius: 0;
  }
  .dropdown-toggle::after {
    display: inline-block; margin-left: 0.255em; vertical-align: 0.255em; content: "";
    border-top: 0.3em solid; border-right: 0.3em solid transparent; border-bottom: 0; border-left: 0.3em solid transparent;
  }
  .dropdown-menu {
    position: absolute; top: 100%; left: 0; z-index: 1000; display: none; min-width: 10rem;
    padding: 0.5rem 0; margin: 0.125rem 0 0; list-style: none; background-color: #fff;
    border: 1px solid rgba(0,0,0,.175); border-radius: 0.375rem;
  }
  .dropdown-menu.show { display: block; }
  .dropdown-item { display: block; width: 100%; padding: 0.25rem 1rem; color: #212529; text-decoration: none; }
</style>
</head>
<body>
<section>
  <div id="grp-basic" class="btn-group" role="group">
    <button id="b1" type="button" class="btn btn-primary">Apple</button>
    <button id="b2" type="button" class="btn btn-primary">Samsung</button>
    <button id="b3" type="button" class="btn btn-primary">Sony</button>
  </div>
</section>

<section style="margin-top:16px">
  <div id="grp-lg" class="btn-group btn-group-lg">
    <button id="lg-1" type="button" class="btn btn-primary">Apple</button>
    <button type="button" class="btn btn-primary">Samsung</button>
  </div>
  <div id="grp-sm" class="btn-group btn-group-sm">
    <button id="sm-1" type="button" class="btn btn-primary">Apple</button>
    <button type="button" class="btn btn-primary">Samsung</button>
  </div>
</section>

<section style="margin-top:16px">
  <div id="grp-vert" class="btn-group-vertical">
    <button id="v1" type="button" class="btn btn-primary">Apple</button>
    <button id="v2" type="button" class="btn btn-primary">Samsung</button>
    <button id="v3" type="button" class="btn btn-primary">Sony</button>
  </div>
</section>

<section style="margin-top:16px">
  <div id="grp-nested-h" class="btn-group">
    <button type="button" class="btn btn-primary">Apple</button>
    <button type="button" class="btn btn-primary">Samsung</button>
    <div class="btn-group">
      <button id="h-toggle" type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">Sony</button>
      <div id="h-menu" class="dropdown-menu">
        <a class="dropdown-item" href="#">Tablet</a>
        <a class="dropdown-item" href="#">Smartphone</a>
      </div>
    </div>
  </div>
</section>

<section style="margin-top:48px">
  <div id="grp-nested-v" class="btn-group-vertical">
    <button type="button" class="btn btn-primary">Apple</button>
    <button type="button" class="btn btn-primary">Samsung</button>
    <div class="btn-group">
      <button id="v-toggle" type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">Sony</button>
      <ul id="v-menu" class="dropdown-menu">
        <li><a class="dropdown-item" href="#">Tablet</a></li>
        <li><a class="dropdown-item" href="#">Smartphone</a></li>
      </ul>
    </div>
  </div>
</section>

<section style="margin-top:48px">
  <div id="inline-g1" class="btn-group">
    <button type="button" class="btn btn-primary">Apple</button>
    <button type="button" class="btn btn-primary">Samsung</button>
    <button type="button" class="btn btn-primary">Sony</button>
  </div>
  <div id="inline-g2" class="btn-group">
    <button type="button" class="btn btn-primary">BMW</button>
    <button type="button" class="btn btn-primary">Mercedes</button>
    <button type="button" class="btn btn-primary">Volvo</button>
  </div>
</section>

<script>
  document.querySelectorAll('[data-bs-toggle="dropdown"]').forEach(btn => {
    btn.addEventListener("click", () => {
      const menu = btn.nextElementSibling;
      const open = menu.classList.toggle("show");
      btn.setAttribute("aria-expanded", String(open));
    });
  });
</script>
</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():
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 1000, "height": 800})
        page.set_content(HTML, wait_until="load")

        # Case 1: basic horizontal btn-group
        c1_actual = page.evaluate("""() => {
            const g = getComputedStyle(document.getElementById("grp-basic"));
            const r1 = document.getElementById("b1").getBoundingClientRect();
            const r2 = document.getElementById("b2").getBoundingClientRect();
            const r3 = document.getElementById("b3").getBoundingClientRect();
            const s1 = getComputedStyle(document.getElementById("b1"));
            const s2 = getComputedStyle(document.getElementById("b2"));
            const s3 = getComputedStyle(document.getElementById("b3"));
            return {
                display: g.display,
                same_row: Math.round(r1.top) === Math.round(r2.top) && Math.round(r2.top) === Math.round(r3.top),
                b2_margin_left: s2.marginLeft,
                b1_outer_left_radius: s1.borderTopLeftRadius,
                b1_inner_right_radius: s1.borderTopRightRadius,
                b2_inner_left_radius: s2.borderTopLeftRadius,
                b3_outer_right_radius: s3.borderTopRightRadius,
            };
        }""")
        c1_expected = {
            "display": "inline-flex",
            "same_row": True,
            "b2_margin_left": "-1px",
            "b1_outer_left_radius": "6px",
            "b1_inner_right_radius": "0px",
            "b2_inner_left_radius": "0px",
            "b3_outer_right_radius": "6px",
        }

        # Case 2: btn-group sizes + vertical group
        c2_actual = page.evaluate("""() => {
            const lgH = Math.round(document.getElementById("lg-1").getBoundingClientRect().height);
            const mdH = Math.round(document.getElementById("b1").getBoundingClientRect().height);
            const smH = Math.round(document.getElementById("sm-1").getBoundingClientRect().height);
            const gv = getComputedStyle(document.getElementById("grp-vert"));
            const v1 = document.getElementById("v1").getBoundingClientRect();
            const v2 = document.getElementById("v2").getBoundingClientRect();
            const v3 = document.getElementById("v3").getBoundingClientRect();
            return {
                lg_fs: getComputedStyle(document.getElementById("lg-1")).fontSize,
                sm_fs: getComputedStyle(document.getElementById("sm-1")).fontSize,
                strict_size_order: lgH > mdH && mdH > smH,
                vert_flex_dir: gv.flexDirection,
                vert_stacked: v2.top > v1.top && v3.top > v2.top,
                vert_equal_width: Math.round(v1.width) === Math.round(v2.width) && Math.round(v2.width) === Math.round(v3.width),
            };
        }""")
        c2_expected = {
            "lg_fs": "20px",
            "sm_fs": "14px",
            "strict_size_order": True,
            "vert_flex_dir": "column",
            "vert_stacked": True,
            "vert_equal_width": True,
        }

        # Case 3: nested dropdown in horizontal & vertical groups
        h_before = page.evaluate('getComputedStyle(document.getElementById("h-menu")).display')
        page.click("#h-toggle")
        h_after = page.evaluate("""() => ({
            display: getComputedStyle(document.getElementById("h-menu")).display,
            expanded: document.getElementById("h-toggle").getAttribute("aria-expanded"),
            items: document.querySelectorAll("#h-menu .dropdown-item").length,
        })""")
        page.click("#h-toggle")
        h_closed = page.evaluate('getComputedStyle(document.getElementById("h-menu")).display')

        v_before = page.evaluate('getComputedStyle(document.getElementById("v-menu")).display')
        page.click("#v-toggle")
        v_after = page.evaluate("""() => ({
            display: getComputedStyle(document.getElementById("v-menu")).display,
            expanded: document.getElementById("v-toggle").getAttribute("aria-expanded"),
            items: document.querySelectorAll("#v-menu .dropdown-item").length,
        })""")
        c3_actual = {
            "h_before": h_before,
            "h_open_display": h_after["display"],
            "h_open_expanded": h_after["expanded"],
            "h_items": h_after["items"],
            "h_closed": h_closed,
            "v_before": v_before,
            "v_open_display": v_after["display"],
            "v_open_expanded": v_after["expanded"],
            "v_items": v_after["items"],
        }
        c3_expected = {
            "h_before": "none",
            "h_open_display": "block",
            "h_open_expanded": "true",
            "h_items": 2,
            "h_closed": "none",
            "v_before": "none",
            "v_open_display": "block",
            "v_open_expanded": "true",
            "v_items": 2,
        }

        # Case 4: multiple inline button groups
        c4_actual = page.evaluate("""() => {
            const g1 = document.getElementById("inline-g1").getBoundingClientRect();
            const g2 = document.getElementById("inline-g2").getBoundingClientRect();
            return {
                side_by_side_same_top: Math.round(g1.top) === Math.round(g2.top),
                g2_to_right_of_g1: g2.left >= g1.right,
            };
        }""")
        c4_expected = {"side_by_side_same_top": True, "g2_to_right_of_g1": True}

        browser.close()

    cases = [
        dict(name="basic_group_and_border_radius", description="核对 .btn-group 水平 inline-flex 排列、-1px 边框重叠与内侧圆角归零", expected=c1_expected, actual=c1_actual, passed=c1_actual == c1_expected),
        dict(name="group_sizes_and_vertical", description="核对 .btn-group-lg/sm 尺寸缩放与 .btn-group-vertical 等宽垂直堆叠", expected=c2_expected, actual=c2_actual, passed=c2_actual == c2_expected),
        dict(name="nested_dropdown_horizontal_and_vertical", description="核对水平与垂直按钮组内嵌 data-bs-toggle=dropdown 菜单展开/收起状态", expected=c3_expected, actual=c3_actual, passed=c3_actual == c3_expected),
        dict(name="inline_multiple_groups", description="核对多个独立 .btn-group 并列显示在同一行", expected=c4_expected, actual=c4_actual, passed=c4_actual == c4_expected),
    ]
    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对 inline-flex 水平排列、-1px 边框重叠、lg/sm 尺寸梯度、垂直等宽堆叠、data-bs-toggle 下拉切换及多组同行并列。
在离线 Chromium 中验证水平/垂直按钮组、尺寸缩放与内嵌下拉菜单

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

当前源码 SHA256:46b200dbdf5fc80a853c072809186616e8d24bfed992eabbcfbebaf225c4d48f

下载本站示例源码

本地运行

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

下载Bootstrap5 按钮组实验

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

ZIP SHA256:813801265f4f88d65cead7b7d3a619b36701d0ca21045891c5b05448c2203885

常见错误与边界

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

练习与解答

在 `.btn-group` 内嵌套下拉菜单时,为什么必须用内层 `.btn-group` 包裹触发按钮与 `.dropdown-menu`?

展开参考解答

内层 `.btn-group` 既为绝对定位的 `.dropdown-menu` 提供定位参考容器(`position: relative`),又能让外层 `.btn-group` 的首尾圆角和 `-1px` 边框折叠规则正确作用到下拉触发按钮上。

规范与官方依据