Bootstrap5 按钮
核对 Bootstrap 5 语义按钮、轮廓按钮、三档尺寸、d-grid/gap 块级按钮、激活/禁用态与加载旋转按钮的实测渲染。
学完这一章,你能够
- 核对 Bootstrap 5 语义按钮、轮廓按钮、三档尺寸、d-grid/gap 块级按钮、激活/禁用态与加载旋转按钮的实测渲染。
语义按钮样式与适用标签
Bootstrap 5 以基础类 `.btn` 定义按钮的内边距、字号与圆角,再叠加语义变体类呈现不同业务含义,包括 `.btn-primary`、`.btn-secondary`、`.btn-success`、`.btn-info`、`.btn-warning`、`.btn-danger`、`.btn-dark`、`.btn-light` 以及链接外观的 `.btn-link`。本站离线 Chromium 实测确认 `.btn-primary` 背景为 `rgb(13, 110, 253)`、`.btn-success` 为 `rgb(25, 135, 84)`、`.btn-danger` 为 `rgb(220, 53, 69)`、`.btn-warning` 为 `rgb(255, 193, 7)`,`.btn-link` 背景透明且文字为 `rgb(13, 110, 253)`。
按钮类不仅限于 `<button>`,同样可作用于 `<a>`(建议补充 `role="button"`)及 `<input type="button|submit|reset">`。实测这 5 种标签在应用 `.btn.btn-info` 后均输出一致的 `rgb(13, 202, 240)` 背景与 `6px` 圆角。
轮廓边框按钮与尺寸梯度
使用 `.btn-outline-*` 系列(如 `.btn-outline-primary` 至 `.btn-outline-light`)可创建透明底色、彩色边框的轮廓按钮;浅色轮廓按钮在白底页面上通常搭配 `.text-dark`(文字 `rgb(33, 37, 41)`)保障可读性。实测 `.btn-outline-primary` 常态背景为 `rgba(0, 0, 0, 0)`、文字为 `rgb(13, 110, 253)`,鼠标悬停后切换为蓝色实底白字。
按钮提供三档尺寸:默认 `.btn` 字号 `16px`,`.btn-lg` 放大至 `20px`,`.btn-sm` 缩小至 `14px`,实测渲染高度严格满足 `btn-lg > 默认 > btn-sm`。
块级按钮与网格间距(BS5 变更)
需要特别注意:Bootstrap 5 已正式移除 Bootstrap 4 的 `.btn-block` 类,单独为按钮添加 `.btn-block` 不会撑满父容器;全宽块级按钮应由父级 `.d-grid`(`display: grid`)统一驱动。实测在 `600px` 容器中,仅挂 `.btn-block` 的按钮宽度保持内容固有宽度(`< 300px`),而放入 `.d-grid` 后按钮宽度精确拉满至 `600px`。
当 `.d-grid` 内堆叠多个全宽按钮时,直接为父容器附加 `.gap-*` 工具类控制纵向间距;实测 `.d-grid.gap-3` 产生 `rowGap: 16px`,相邻按钮实测竖直间隙为 `16px`。
激活禁用状态与加载按钮
`.active` 类使按钮呈现按下高亮态(实测 `.btn-primary.active` 背景加深至 `rgb(10, 88, 202)`)。原生 `<button>` 使用布尔属性 `disabled` 阻止交互并降至 `opacity: 0.65`(实测点击计数为 `0`);而 `<a>` 不支持原生 `disabled` 属性,须改用 `.disabled` 类(设置 `pointer-events: none` 与 `opacity: 0.65`,并配合 `aria-disabled="true"`)禁用链接点击。
在按钮内部嵌套 `.spinner-border.spinner-border-sm` 或 `.spinner-grow.spinner-grow-sm` 可构建提交中/加载中按钮,常与 `disabled` 组合防止重复提交。实测两种小号加载图标在按钮内的布局尺寸均为 `16px × 16px`。
在离线 Chromium 中验证语义按钮、轮廓悬停、d-grid 块级按钮及加载态
"""Offline Playwright Chromium verification for Bootstrap 5 Buttons (Ch 11)."""
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;
color: #212529;
text-align: center;
text-decoration: none;
vertical-align: middle;
cursor: pointer;
user-select: none;
background-color: transparent;
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-primary.active { color: #fff; background-color: #0a58ca; border-color: #0a53be; }
.btn-secondary { color: #fff; background-color: #6c757d; border-color: #6c757d; }
.btn-success { color: #fff; background-color: #198754; border-color: #198754; }
.btn-info { color: #000; background-color: #0dcaf0; border-color: #0dcaf0; }
.btn-warning { color: #000; background-color: #ffc107; border-color: #ffc107; }
.btn-danger { color: #fff; background-color: #dc3545; border-color: #dc3545; }
.btn-dark { color: #fff; background-color: #212529; border-color: #212529; }
.btn-light { color: #000; background-color: #f8f9fa; border-color: #f8f9fa; }
.btn-link { color: #0d6efd; text-decoration: underline; background-color: transparent; border-color: transparent; }
.btn-outline-primary { color: #0d6efd; border-color: #0d6efd; background-color: transparent; }
.btn-outline-primary:hover { color: #fff; background-color: #0d6efd; border-color: #0d6efd; }
.btn-outline-secondary { color: #6c757d; border-color: #6c757d; }
.btn-outline-success { color: #198754; border-color: #198754; }
.btn-outline-info { color: #0dcaf0; border-color: #0dcaf0; }
.btn-outline-warning { color: #ffc107; border-color: #ffc107; }
.btn-outline-danger { color: #dc3545; border-color: #dc3545; }
.btn-outline-dark { color: #212529; border-color: #212529; }
.btn-outline-light { color: #f8f9fa; border-color: #f8f9fa; }
.text-dark { color: #212529 !important; }
.btn-lg { padding: 0.5rem 1rem; font-size: 1.25rem; border-radius: 0.5rem; }
.btn-sm { padding: 0.25rem 0.5rem; font-size: 0.875rem; border-radius: 0.25rem; }
/* Bootstrap 5 removed .btn-block; block buttons rely on .d-grid + .gap-* */
.d-grid { display: grid !important; }
.gap-3 { gap: 1rem !important; }
.btn:disabled, .btn.disabled { pointer-events: none; opacity: 0.65; }
@keyframes spinner-border { to { transform: rotate(360deg); } }
@keyframes spinner-grow {
0% { transform: scale(0); opacity: 0; }
50% { opacity: 1; }
100% { transform: scale(1); opacity: 0; }
}
.spinner-border {
display: inline-block; width: 2rem; height: 2rem; vertical-align: -0.125em;
border: 0.25em solid currentColor; border-right-color: transparent; border-radius: 50%;
animation: 0.75s linear infinite spinner-border;
}
.spinner-border-sm { width: 1rem; height: 1rem; border-width: 0.2em; }
.spinner-grow {
display: inline-block; width: 2rem; height: 2rem; vertical-align: -0.125em;
background-color: currentColor; border-radius: 50%;
animation: 0.75s linear infinite spinner-grow;
}
.spinner-grow-sm { width: 1rem; height: 1rem; }
.wrap-600 { width: 600px; }
</style>
</head>
<body>
<section id="sec-variants">
<button id="b-base" type="button" class="btn">基本按钮</button>
<button id="b-primary" type="button" class="btn btn-primary">主要按钮</button>
<button id="b-secondary" type="button" class="btn btn-secondary">次要按钮</button>
<button id="b-success" type="button" class="btn btn-success">成功</button>
<button id="b-info" type="button" class="btn btn-info">信息</button>
<button id="b-warning" type="button" class="btn btn-warning">警告</button>
<button id="b-danger" type="button" class="btn btn-danger">危险</button>
<button id="b-dark" type="button" class="btn btn-dark">黑色</button>
<button id="b-light" type="button" class="btn btn-light">浅色</button>
<button id="b-link" type="button" class="btn btn-link">链接</button>
</section>
<section id="sec-elements">
<a id="el-a" href="#" class="btn btn-info" role="button">链接按钮</a>
<button id="el-btn" type="button" class="btn btn-info">按钮</button>
<input id="el-input-btn" type="button" class="btn btn-info" value="输入框按钮">
<input id="el-submit" type="submit" class="btn btn-info" value="提交按钮">
<input id="el-reset" type="reset" class="btn btn-info" value="重置按钮">
</section>
<section id="sec-outline">
<button id="o-primary" type="button" class="btn btn-outline-primary">主要按钮</button>
<button id="o-light" type="button" class="btn btn-outline-light text-dark">浅色</button>
</section>
<section id="sec-sizes">
<button id="sz-lg" type="button" class="btn btn-primary btn-lg">大号按钮</button>
<button id="sz-md" type="button" class="btn btn-primary">默认按钮</button>
<button id="sz-sm" type="button" class="btn btn-primary btn-sm">小号按钮</button>
</section>
<section id="sec-grid" class="wrap-600">
<div id="no-grid-wrap">
<button id="legacy-block-only" type="button" class="btn btn-primary btn-block">仅含已废弃 btn-block</button>
</div>
<div id="grid-single" class="d-grid">
<button id="grid-btn-1" type="button" class="btn btn-primary">块级按钮 1</button>
</div>
<div id="grid-multi" class="d-grid gap-3">
<button id="gm-1" type="button" class="btn btn-primary">100% 宽度按钮 1</button>
<button id="gm-2" type="button" class="btn btn-primary">100% 宽度按钮 2</button>
<button id="gm-3" type="button" class="btn btn-primary">100% 宽度按钮 3</button>
</div>
</section>
<section id="sec-states">
<button id="st-active" type="button" class="btn btn-primary active">激活按钮</button>
<button id="st-disabled-btn" type="button" class="btn btn-primary" disabled>禁用按钮</button>
<a id="st-disabled-a" href="#" class="btn btn-primary disabled" tabindex="-1" aria-disabled="true">禁用链接</a>
</section>
<section id="sec-spinners">
<button id="sp-1" type="button" class="btn btn-primary"><span id="sp-icon-1" class="spinner-border spinner-border-sm"></span></button>
<button id="sp-2" type="button" class="btn btn-primary"><span class="spinner-border spinner-border-sm"></span> Loading..</button>
<button id="sp-3" type="button" class="btn btn-primary" disabled><span class="spinner-border spinner-border-sm"></span> Loading..</button>
<button id="sp-4" type="button" class="btn btn-primary" disabled><span id="sp-icon-4" class="spinner-grow spinner-grow-sm"></span> Loading..</button>
</section>
<script>
window.__clicks = 0;
document.getElementById("st-disabled-btn").addEventListener("click", () => { window.__clicks += 1; });
</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: variants + multi-element buttons
c1_actual = page.evaluate("""() => {
const bg = id => getComputedStyle(document.getElementById(id)).backgroundColor;
const col = id => getComputedStyle(document.getElementById(id)).color;
const els = ["el-a", "el-btn", "el-input-btn", "el-submit", "el-reset"];
const allInfoBg = els.every(id => bg(id) === "rgb(13, 202, 240)");
const allRadius = els.every(id => getComputedStyle(document.getElementById(id)).borderTopLeftRadius === "6px");
return {
primary_bg: bg("b-primary"),
success_bg: bg("b-success"),
danger_bg: bg("b-danger"),
warning_bg: bg("b-warning"),
dark_bg: bg("b-dark"),
link_bg: bg("b-link"),
link_color: col("b-link"),
all_five_elements_consistent: allInfoBg && allRadius,
a_role: document.getElementById("el-a").getAttribute("role"),
};
}""")
c1_expected = {
"primary_bg": "rgb(13, 110, 253)",
"success_bg": "rgb(25, 135, 84)",
"danger_bg": "rgb(220, 53, 69)",
"warning_bg": "rgb(255, 193, 7)",
"dark_bg": "rgb(33, 37, 41)",
"link_bg": "rgba(0, 0, 0, 0)",
"link_color": "rgb(13, 110, 253)",
"all_five_elements_consistent": True,
"a_role": "button",
}
# Case 2: outline hover + sizes
outline_before = page.evaluate("""() => {
const s = getComputedStyle(document.getElementById("o-primary"));
return { bg: s.backgroundColor, color: s.color, border: s.borderTopColor };
}""")
page.locator("#o-primary").hover()
outline_after = page.evaluate("""() => {
const s = getComputedStyle(document.getElementById("o-primary"));
return { bg: s.backgroundColor, color: s.color };
}""")
sizes = page.evaluate("""() => {
const m = id => {
const el = document.getElementById(id);
const s = getComputedStyle(el);
return { fs: s.fontSize, pad: s.padding, h: Math.round(el.getBoundingClientRect().height) };
};
const lg = m("sz-lg"), md = m("sz-md"), sm = m("sz-sm");
return {
lg_fs: lg.fs, md_fs: md.fs, sm_fs: sm.fs,
lg_pad: lg.pad, md_pad: md.pad, sm_pad: sm.pad,
strict_height_order: lg.h > md.h && md.h > sm.h,
light_text_dark: getComputedStyle(document.getElementById("o-light")).color,
};
}""")
c2_actual = {
"outline_before_bg": outline_before["bg"],
"outline_before_color": outline_before["color"],
"outline_hover_bg": outline_after["bg"],
"outline_hover_color": outline_after["color"],
"light_text_dark": sizes["light_text_dark"],
"lg_fs": sizes["lg_fs"],
"md_fs": sizes["md_fs"],
"sm_fs": sizes["sm_fs"],
"strict_height_order": sizes["strict_height_order"],
}
c2_expected = {
"outline_before_bg": "rgba(0, 0, 0, 0)",
"outline_before_color": "rgb(13, 110, 253)",
"outline_hover_bg": "rgb(13, 110, 253)",
"outline_hover_color": "rgb(255, 255, 255)",
"light_text_dark": "rgb(33, 37, 41)",
"lg_fs": "20px",
"md_fs": "16px",
"sm_fs": "14px",
"strict_height_order": True,
}
# Case 3: BS5 d-grid + gap-3 vs legacy .btn-block
c3_actual = page.evaluate("""() => {
const legacyW = Math.round(document.getElementById("legacy-block-only").getBoundingClientRect().width);
const gridBtnW = Math.round(document.getElementById("grid-btn-1").getBoundingClientRect().width);
const gm1 = document.getElementById("gm-1").getBoundingClientRect();
const gm2 = document.getElementById("gm-2").getBoundingClientRect();
const multiStyle = getComputedStyle(document.getElementById("grid-multi"));
return {
legacy_btn_block_is_not_full_width: legacyW < 300,
d_grid_button_width_px: gridBtnW,
multi_display: multiStyle.display,
multi_row_gap: multiStyle.rowGap,
measured_gap_px: Math.round(gm2.top - gm1.bottom),
};
}""")
c3_expected = {
"legacy_btn_block_is_not_full_width": True,
"d_grid_button_width_px": 600,
"multi_display": "grid",
"multi_row_gap": "16px",
"measured_gap_px": 16,
}
# Case 4: active, disabled button vs disabled link, loading spinner buttons
page.evaluate("""() => { document.getElementById("st-disabled-btn").click(); }""")
c4_actual = page.evaluate("""() => {
const act = getComputedStyle(document.getElementById("st-active"));
const disBtn = document.getElementById("st-disabled-btn");
const disBtnStyle = getComputedStyle(disBtn);
const disA = getComputedStyle(document.getElementById("st-disabled-a"));
const sp1 = getComputedStyle(document.getElementById("sp-icon-1"));
const sp4 = getComputedStyle(document.getElementById("sp-icon-4"));
return {
active_bg: act.backgroundColor,
disabled_btn_prop: disBtn.disabled,
disabled_btn_opacity: disBtnStyle.opacity,
disabled_btn_clicks: window.__clicks,
disabled_link_pointer_events: disA.pointerEvents,
disabled_link_opacity: disA.opacity,
spinner_border_sm_wh: [sp1.width, sp1.height],
spinner_grow_sm_wh: [sp4.width, sp4.height],
loading_disabled_count: document.querySelectorAll("#sec-spinners button:disabled").length,
};
}""")
c4_expected = {
"active_bg": "rgb(10, 88, 202)",
"disabled_btn_prop": True,
"disabled_btn_opacity": "0.65",
"disabled_btn_clicks": 0,
"disabled_link_pointer_events": "none",
"disabled_link_opacity": "0.65",
"spinner_border_sm_wh": ["16px", "16px"],
"spinner_grow_sm_wh": ["16px", "16px"],
"loading_disabled_count": 2,
}
browser.close()
cases = [
dict(name="button_variants_and_elements", description="核对语义按钮颜色与 a/button/input 元素统一渲染", expected=c1_expected, actual=c1_actual, passed=c1_actual == c1_expected),
dict(name="button_outline_and_sizes", description="核对轮廓按钮悬停反色与 btn-lg/默认/btn-sm 尺寸梯度", expected=c2_expected, actual=c2_actual, passed=c2_actual == c2_expected),
dict(name="button_block_d_grid_gap", description="核对 BS5 移除 btn-block 后由 d-grid 与 gap-3 控制块级按钮", expected=c3_expected, actual=c3_actual, passed=c3_actual == c3_expected),
dict(name="button_states_and_spinner", description="核对 active/disabled 状态、a.disabled 禁用及加载按钮内嵌旋转器", 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()
- 核对 5 种元素统一渲染、轮廓按钮悬停反色、d-grid 600px 撑满与 gap-3 16px 间距、disabled 拦截点击及 16px 旋转器。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:56b56359331b7a6c2a5d6ef431f2db08f9958f422d766b78d237d72be8ceac92
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:a81a054ec4b7080a06e788600596fc61f529a8bc40608d6ade3fe267d8ea2584
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
Bootstrap 5 为什么推荐用父级 `.d-grid` 代替 `.btn-block` 实现块级按钮?禁用 `<a>` 按钮与 `<button>` 按钮有何区别?
展开参考解答
Bootstrap 5 移除了 `.btn-block`,改由 CSS Grid 工具类 `.d-grid` 与 `.gap-*` 统一控制单/多按钮撑满与间距;`<button>` 直接支持原生 `disabled` 属性拦截点击与表单提交,`<a>` 不支持该属性,需用 `.disabled` 类(`pointer-events: none`)并配合 `aria-disabled="true"` 与 `tabindex="-1"`。