Bootstrap4 按钮组
核对 Bootstrap 4 按钮组的水平并排、尺寸缩放、垂直堆叠、内嵌与拆分下拉菜单及多组并列布局,并结合离线 Chromium 实测数据说明样式机理。
学完这一章,你能够
- 核对 Bootstrap 4 按钮组的水平并排、尺寸缩放、垂直堆叠、内嵌与拆分下拉菜单及多组并列布局,并结合离线 Chromium 实测数据说明样式机理。
基础水平按钮组与多组并列
在 Bootstrap 4 中,将多个 `.btn` 按钮包裹在带有 `.btn-group` 类的 `<div>` 容器内即可使按钮紧贴排布在同一行。本站离线 Chromium 实测表明,`.btn-group` 采用 `display: inline-flex`,相邻按钮通过 `margin-left: -1px` 合并共用边框,同时中间按钮左右圆角均收敛为 `0px`,只保留首尾按钮的外侧圆角。
由于 `.btn-group` 本身是行内弹性容器(`inline-flex`),页面中连续声明多个按钮组时会自动在同一行并列展示。实测将两组各含 3 个主色按钮的 `.btn-group` 连续放置后,两组顶部对齐且第二组左边界紧随第一组右侧。
尺寸缩放与垂直按钮组
无需为组内每个按钮单独指定尺寸,直接在 `.btn-group` 上追加 `.btn-group-lg` 或 `.btn-group-sm` 即可统一缩放整组按钮。实测三档尺寸的计算字号与按钮高度依次递增:`.btn-group-sm` 为 `14px` / `31px`,默认 `.btn-group` 为 `16px` / `38px`,`.btn-group-lg` 为 `20px` / `48px`。
若需要将按钮纵向堆叠排列,可用 `.btn-group-vertical` 替代 `.btn-group`。实测 `.btn-group-vertical` 将主轴设为 `flex-direction: column`,组内按钮等宽并沿纵向依次排列,相邻按钮通过 `margin-top: -1px` 消除双边框,首项底部圆角与末项顶部圆角归零为 `0px`。
内嵌下拉、拆分按钮与垂直下拉组合
在水平按钮组内部可再嵌套一层 `.btn-group`,放置带有 `.dropdown-toggle` 与 `data-toggle="dropdown"` 的触发按钮及 `.dropdown-menu` 菜单容器,从而在不破坏外层连续边框的前提下挂接下拉选项。
当需要区分“主动作点击”与“展开更多操作”时,可使用拆分按钮下拉菜单:主按钮与紧邻的 `.dropdown-toggle.dropdown-toggle-split` 按钮同置于 `.btn-group` 内,触发按钮以更紧凑的左右内边距专门显示下拉箭头(Bootstrap 4 通过伪元素 `::after` 绘制箭头,传统 `<span class="caret">` 仅作兼容占位,无障碍场景建议放 `.sr-only` 文本)。同样地,`.btn-group-vertical` 内也可嵌套带下拉菜单的子 `.btn-group`。本站点击实测显示,内嵌、拆分与垂直三类菜单初始均为 `display: none`,点击触发器后全部切换为 `display: block` 且 `aria-expanded` 变为 `true`,拆分触发器宽度显著小于主按钮。
运行 Bootstrap 4 按钮组布局、尺寸与下拉交互 Chromium 离线实验
"""Offline Playwright Chromium verification for Bootstrap 4 Button Groups."""
import json
from playwright.sync_api import sync_playwright
CSS = """
*, *::before, *::after { box-sizing: border-box; }
body { margin: 16px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; font-size: 16px; line-height: 1.5; }
.btn {
display: inline-block; font-weight: 400; color: #212529; text-align: center;
vertical-align: middle; user-select: none; background-color: transparent;
border: 1px solid transparent; padding: 0.375rem 0.75rem; font-size: 1rem;
line-height: 1.5; border-radius: 0.25rem; cursor: pointer;
}
.btn-primary { color: #fff; background-color: #007bff; border-color: #007bff; }
.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:not(:first-child),
.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; line-height: 1.5; border-radius: 0.3rem; }
.btn-group-sm > .btn { padding: 0.25rem 0.5rem; font-size: 0.875rem; line-height: 1.5; border-radius: 0.2rem; }
.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; margin-left: 0; }
.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:not(:first-child),
.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-toggle-split { padding-right: 0.5625rem; padding-left: 0.5625rem; }
.dropdown-toggle-split::after { margin-left: 0; }
.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; font-size: 1rem; color: #212529;
background-color: #fff; border: 1px solid rgba(0,0,0,.15); border-radius: 0.25rem;
}
.dropdown-menu.show { display: block; }
.dropdown-item { display: block; width: 100%; padding: 0.25rem 1.5rem; color: #212529; text-decoration: none; }
.row-box { margin-bottom: 16px; }
"""
HTML = f"""<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><style>{CSS}</style></head>
<body>
<div class="row-box" id="inline-row">
<div class="btn-group" id="g-basic">
<button type="button" class="btn btn-primary" id="b-apple">Apple</button>
<button type="button" class="btn btn-primary" id="b-samsung">Samsung</button>
<button type="button" class="btn btn-primary" id="b-sony">Sony</button>
</div>
<div class="btn-group" id="g-second">
<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>
</div>
<div class="row-box">
<div class="btn-group btn-group-sm" id="g-sm"><button type="button" class="btn btn-primary">Sm</button></div>
<div class="btn-group" id="g-md"><button type="button" class="btn btn-primary">Md</button></div>
<div class="btn-group btn-group-lg" id="g-lg"><button type="button" class="btn btn-primary">Lg</button></div>
</div>
<div class="row-box">
<div class="btn-group-vertical" id="g-vert">
<button type="button" class="btn btn-primary" id="v1">Apple</button>
<button type="button" class="btn btn-primary" id="v2">Samsung</button>
<button type="button" class="btn btn-primary" id="v3">Sony</button>
</div>
</div>
<div class="row-box" style="display:flex; gap:200px; align-items:flex-start;">
<div class="btn-group" id="g-nested">
<button type="button" class="btn btn-primary">Apple</button>
<button type="button" class="btn btn-primary">Samsung</button>
<div class="btn-group">
<button type="button" class="btn btn-primary dropdown-toggle" id="t-nested" data-toggle="dropdown" aria-expanded="false">Sony</button>
<div class="dropdown-menu" id="m-nested">
<a class="dropdown-item" href="#">Tablet</a>
<a class="dropdown-item" href="#">Smartphone</a>
</div>
</div>
</div>
<div class="btn-group" id="g-split">
<button type="button" class="btn btn-primary" id="split-main">Sony</button>
<button type="button" class="btn btn-primary dropdown-toggle dropdown-toggle-split" id="t-split" data-toggle="dropdown" aria-expanded="false">
<span class="caret"></span>
</button>
<div class="dropdown-menu" id="m-split">
<a class="dropdown-item" href="#">Tablet</a>
<a class="dropdown-item" href="#">Smartphone</a>
</div>
</div>
<div class="btn-group-vertical" id="g-vdrop">
<button type="button" class="btn btn-primary">Apple</button>
<button type="button" class="btn btn-primary">Samsung</button>
<div class="btn-group">
<button type="button" class="btn btn-primary dropdown-toggle" id="t-vdrop" data-toggle="dropdown" aria-expanded="false">Sony</button>
<div class="dropdown-menu" id="m-vdrop">
<a class="dropdown-item" href="#">Tablet</a>
<a class="dropdown-item" href="#">Smartphone</a>
</div>
</div>
</div>
</div>
<script>
document.querySelectorAll('[data-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)
try:
page = browser.new_page(viewport={"width": 1200, "height": 800})
page.set_content(HTML, wait_until="load")
c1_actual = page.evaluate("""() => {
const g1 = document.getElementById('g-basic');
const g2 = document.getElementById('g-second');
const b1 = document.getElementById('b-apple');
const b2 = document.getElementById('b-samsung');
const b3 = document.getElementById('b-sony');
const r1 = b1.getBoundingClientRect(), r2 = b2.getBoundingClientRect(), r3 = b3.getBoundingClientRect();
const rg1 = g1.getBoundingClientRect(), rg2 = g2.getBoundingClientRect();
return {
group_display: getComputedStyle(g1).display,
same_row_buttons: Math.abs(r1.top - r2.top) < 1 && Math.abs(r2.top - r3.top) < 1,
second_btn_margin_left: getComputedStyle(b2).marginLeft,
middle_radii: [getComputedStyle(b2).borderTopLeftRadius, getComputedStyle(b2).borderTopRightRadius],
inline_side_by_side: Math.abs(rg1.top - rg2.top) < 1 && rg2.left > rg1.right
};
}""")
c1_exp = {
"group_display": "inline-flex",
"same_row_buttons": True,
"second_btn_margin_left": "-1px",
"middle_radii": ["0px", "0px"],
"inline_side_by_side": True,
}
c2_actual = page.evaluate("""() => {
const sm = document.querySelector('#g-sm .btn');
const md = document.querySelector('#g-md .btn');
const lg = document.querySelector('#g-lg .btn');
const hs = Math.round(sm.getBoundingClientRect().height);
const hm = Math.round(md.getBoundingClientRect().height);
const hl = Math.round(lg.getBoundingClientRect().height);
return {
font_sizes: [getComputedStyle(sm).fontSize, getComputedStyle(md).fontSize, getComputedStyle(lg).fontSize],
heights_px: [hs, hm, hl],
ordered: hs < hm && hm < hl
};
}""")
c2_exp = {
"font_sizes": ["14px", "16px", "20px"],
"heights_px": [31, 38, 48],
"ordered": True,
}
c3_actual = page.evaluate("""() => {
const gv = document.getElementById('g-vert');
const v1 = document.getElementById('v1');
const v2 = document.getElementById('v2');
const v3 = document.getElementById('v3');
const r1 = v1.getBoundingClientRect(), r2 = v2.getBoundingClientRect(), r3 = v3.getBoundingClientRect();
return {
flex_direction: getComputedStyle(gv).flexDirection,
stacked_vertically: r2.top > r1.top && r3.top > r2.top,
equal_width: Math.abs(r1.width - r2.width) < 1 && Math.abs(r2.width - r3.width) < 1,
v2_margin_top: getComputedStyle(v2).marginTop,
v1_bottom_radius: getComputedStyle(v1).borderBottomLeftRadius,
v3_top_radius: getComputedStyle(v3).borderTopLeftRadius
};
}""")
c3_exp = {
"flex_direction": "column",
"stacked_vertically": True,
"equal_width": True,
"v2_margin_top": "-1px",
"v1_bottom_radius": "0px",
"v3_top_radius": "0px",
}
before_disp = page.evaluate("""() => [
getComputedStyle(document.getElementById('m-nested')).display,
getComputedStyle(document.getElementById('m-split')).display,
getComputedStyle(document.getElementById('m-vdrop')).display
]""")
page.click("#t-nested")
page.click("#t-split")
page.click("#t-vdrop")
after = page.evaluate("""() => {
const mainW = document.getElementById('split-main').getBoundingClientRect().width;
const splitW = document.getElementById('t-split').getBoundingClientRect().width;
return {
after_displays: [
getComputedStyle(document.getElementById('m-nested')).display,
getComputedStyle(document.getElementById('m-split')).display,
getComputedStyle(document.getElementById('m-vdrop')).display
],
aria_expanded: [
document.getElementById('t-nested').getAttribute('aria-expanded'),
document.getElementById('t-split').getAttribute('aria-expanded'),
document.getElementById('t-vdrop').getAttribute('aria-expanded')
],
split_narrower_than_main: splitW < mainW,
nested_items_count: document.querySelectorAll('#m-nested .dropdown-item').length
};
}""")
c4_actual = {"before_displays": before_disp, **after}
c4_exp = {
"before_displays": ["none", "none", "none"],
"after_displays": ["block", "block", "block"],
"aria_expanded": ["true", "true", "true"],
"split_narrower_than_main": True,
"nested_items_count": 2,
}
cases = [
{"name": "horizontal_and_inline_groups", "input": ".btn-group horizontal & adjacent inline groups", "expected": c1_exp, "actual": c1_actual, "passed": c1_actual == c1_exp},
{"name": "button_group_sizing", "input": ".btn-group-sm / default / .btn-group-lg", "expected": c2_exp, "actual": c2_actual, "passed": c2_actual == c2_exp},
{"name": "vertical_button_group", "input": ".btn-group-vertical 3 buttons", "expected": c3_exp, "actual": c3_actual, "passed": c3_actual == c3_exp},
{"name": "nested_split_and_vertical_dropdowns", "input": "click nested, split & vertical dropdown toggles", "expected": c4_exp, "actual": c4_actual, "passed": c4_actual == c4_exp},
]
print(json.dumps({"cases": cases}, ensure_ascii=False))
finally:
browser.close()
if __name__ == "__main__":
main()
- 核对水平/并列 inline-flex 与 -1px 边框合并、sm/默认/lg 高度 31/38/48px、垂直等宽堆叠,以及内嵌/拆分/垂直三类下拉菜单点击切换。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:96120e65fe759a0427a617909b0ddafa591cdf0b3a68088e8d97cb62d5fa12f4
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:fc7148c41403fb14e59d311f98893085187abc8243dd8736b588aade07585133
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么 Bootstrap 4 水平按钮组内相邻按钮不会出现双倍粗边框?拆分下拉按钮相比普通内嵌下拉有何交互优势?
展开参考解答
`.btn-group` 为非首个按钮应用 `margin-left: -1px` 使相邻 1px 边框重叠,并将内侧圆角置零;拆分按钮把主操作和 `.dropdown-toggle-split` 下拉触发拆成两个独立按钮,用户可直接执行默认动作而不必先展开菜单。