Bootstrap4 徽章(Badges)
核对 Bootstrap 4 徽章随父元素字号缩放、8 种语义配色、药丸圆角样式(含旧版 .badge-default 差异)以及嵌入按钮时的定位表现。
学完这一章,你能够
- 核对 Bootstrap 4 徽章随父元素字号缩放、8 种语义配色、药丸圆角样式(含旧版 .badge-default 差异)以及嵌入按钮时的定位表现。
基础徽章与随父元素缩放机制
徽章(Badges)常用于标注新增、未读数量或轻量状态标签。在 `<span>` 上组合基础类 `.badge` 与语义配色类(如 `.badge-secondary`)即可生效。由于 `.badge` 采用相对字号 `font-size: 75%` 与相对内边距 `0.25em 0.4em`,它会自动跟随父级容器缩放:本站离线 Chromium 实测 `<h1>`–`<h6>`(`40px` 至 `16px`)内的徽章计算字号依次为 `30px`、`24px`、`21px`、`18px`、`15px`、`12px`,均严格保持 `0.75` 的缩放比例。
语义配色与药丸形状徽章
Bootstrap 4 内置 8 种语义颜色类:`.badge-primary`、`.badge-secondary`、`.badge-success`、`.badge-danger`、`.badge-warning`、`.badge-info`、`.badge-light` 与 `.badge-dark`。实测深色背景类均自动配白字 `rgb(255, 255, 255)`,而 `.badge-warning`(`rgb(255, 193, 7)`)与 `.badge-light`(`rgb(248, 249, 250)`)自动配深灰文字 `rgb(33, 37, 41)` 以保证可读对比度。
追加 `.badge-pill` 类可将标准小圆角(实测 `4px`)调整为两端完全半圆的药丸形状(`border-radius: 10rem`,计算值 `160px`),并适当加宽左右内边距至 `0.6em`。需注意 Bootstrap 3 时代的 `.badge-default` 在 Bootstrap 4 中已被移除,实测单独使用 `.badge-default` 背景为透明 `rgba(0, 0, 0, 0)`,实际开发应改用 `.badge-secondary` 等 Bootstrap 4 配色类。
将徽章嵌入按钮内部
将 `<span class="badge badge-light">4</span>` 放入 `<button class="btn btn-primary">` 中可直观呈现未读消息计数。实测 `.btn .badge` 规则会自动应用 `position: relative` 与 `top: -1px` 的微调偏移,使浅色计数徽章(背景 `rgb(248, 249, 250)`)稳妥落在按钮边界内并与文字视觉居中。
运行 Bootstrap 4 徽章缩放、8 种语义色、药丸圆角与按钮内嵌 Chromium 实验
展开查看收起
"""Offline Playwright Chromium verification for Bootstrap 4 Badges."""
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; color: #212529; }
h1 { font-size: 2.5rem; margin: 0 0 8px; }
h2 { font-size: 2rem; margin: 0 0 8px; }
h3 { font-size: 1.75rem; margin: 0 0 8px; }
h4 { font-size: 1.5rem; margin: 0 0 8px; }
h5 { font-size: 1.25rem; margin: 0 0 8px; }
h6 { font-size: 1rem; margin: 0 0 8px; }
.badge {
display: inline-block; padding: 0.25em 0.4em; font-size: 75%; font-weight: 700;
line-height: 1; text-align: center; white-space: nowrap; vertical-align: baseline;
border-radius: 0.25rem;
}
.badge-pill { padding-right: 0.6em; padding-left: 0.6em; border-radius: 10rem; }
.badge-primary { color: #fff; background-color: #007bff; }
.badge-secondary { color: #fff; background-color: #6c757d; }
.badge-success { color: #fff; background-color: #28a745; }
.badge-danger { color: #fff; background-color: #dc3545; }
.badge-warning { color: #212529; background-color: #ffc107; }
.badge-info { color: #fff; background-color: #17a2b8; }
.badge-light { color: #212529; background-color: #f8f9fa; }
.badge-dark { color: #fff; background-color: #343a40; }
.btn {
display: inline-block; padding: 0.375rem 0.75rem; font-size: 1rem; line-height: 1.5;
border: 1px solid transparent; border-radius: 0.25rem;
}
.btn-primary { color: #fff; background-color: #007bff; border-color: #007bff; }
.btn .badge { position: relative; top: -1px; }
"""
HTML = f"""<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><style>{CSS}</style></head>
<body>
<div id="headings">
<h1>测试标题 <span class="badge badge-secondary" id="bh1">New</span></h1>
<h2>测试标题 <span class="badge badge-secondary" id="bh2">New</span></h2>
<h3>测试标题 <span class="badge badge-secondary" id="bh3">New</span></h3>
<h4>测试标题 <span class="badge badge-secondary" id="bh4">New</span></h4>
<h5>测试标题 <span class="badge badge-secondary" id="bh5">New</span></h5>
<h6>测试标题 <span class="badge badge-secondary" id="bh6">New</span></h6>
</div>
<div id="colors">
<span class="badge badge-primary" id="c-primary">主要</span>
<span class="badge badge-secondary" id="c-secondary">次要</span>
<span class="badge badge-success" id="c-success">成功</span>
<span class="badge badge-danger" id="c-danger">危险</span>
<span class="badge badge-warning" id="c-warning">警告</span>
<span class="badge badge-info" id="c-info">信息</span>
<span class="badge badge-light" id="c-light">浅色</span>
<span class="badge badge-dark" id="c-dark">深色</span>
</div>
<div id="pills">
<span class="badge badge-pill badge-default" id="p-default">默认</span>
<span class="badge badge-pill badge-primary" id="p-primary">主要</span>
<span class="badge badge-pill badge-success" id="p-success">成功</span>
<span class="badge badge-pill badge-info" id="p-info">信息</span>
<span class="badge badge-pill badge-warning" id="p-warning">警告</span>
<span class="badge badge-pill badge-danger" id="p-danger">危险</span>
</div>
<button type="button" class="btn btn-primary" id="btn-msg">
Messages <span class="badge badge-light" id="btn-badge">4</span>
</button>
</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": 1000, "height": 800})
page.set_content(HTML, wait_until="load")
c1_actual = page.evaluate("""() => {
const sizes = [1,2,3,4,5,6].map(i => parseFloat(getComputedStyle(document.getElementById('bh'+i)).fontSize));
const parents = [1,2,3,4,5,6].map(i => parseFloat(getComputedStyle(document.querySelector('#headings h'+i)).fontSize));
const ratios = sizes.map((s, idx) => Number((s / parents[idx]).toFixed(2)));
return { badge_px: sizes, parent_px: parents, ratios, strictly_decreasing: sizes.every((v, i) => i === 0 || v < sizes[i-1]) };
}""")
c1_exp = {
"badge_px": [30, 24, 21, 18, 15, 12],
"parent_px": [40, 32, 28, 24, 20, 16],
"ratios": [0.75, 0.75, 0.75, 0.75, 0.75, 0.75],
"strictly_decreasing": True,
}
c2_actual = page.evaluate("""() => {
const keys = ['primary','secondary','success','danger','warning','info','light','dark'];
const out = {};
for (const k of keys) {
const st = getComputedStyle(document.getElementById('c-'+k));
out[k] = [st.backgroundColor, st.color];
}
return out;
}""")
c2_exp = {
"primary": ["rgb(0, 123, 255)", "rgb(255, 255, 255)"],
"secondary": ["rgb(108, 117, 125)", "rgb(255, 255, 255)"],
"success": ["rgb(40, 167, 69)", "rgb(255, 255, 255)"],
"danger": ["rgb(220, 53, 69)", "rgb(255, 255, 255)"],
"warning": ["rgb(255, 193, 7)", "rgb(33, 37, 41)"],
"info": ["rgb(23, 162, 184)", "rgb(255, 255, 255)"],
"light": ["rgb(248, 249, 250)", "rgb(33, 37, 41)"],
"dark": ["rgb(52, 58, 64)", "rgb(255, 255, 255)"],
}
c3_actual = page.evaluate("""() => {
const std = getComputedStyle(document.getElementById('c-primary'));
const pill = getComputedStyle(document.getElementById('p-primary'));
const defPill = getComputedStyle(document.getElementById('p-default'));
return {
std_radius: std.borderRadius,
pill_radius: pill.borderRadius,
pill_padding_x_gt_std: parseFloat(pill.paddingLeft) > parseFloat(std.paddingLeft),
badge_default_bg_transparent: defPill.backgroundColor
};
}""")
c3_exp = {
"std_radius": "4px",
"pill_radius": "160px",
"pill_padding_x_gt_std": True,
"badge_default_bg_transparent": "rgba(0, 0, 0, 0)",
}
c4_actual = page.evaluate("""() => {
const btn = document.getElementById('btn-msg');
const bd = document.getElementById('btn-badge');
const rb = btn.getBoundingClientRect(), rbd = bd.getBoundingClientRect();
const st = getComputedStyle(bd);
return {
position: st.position,
top: st.top,
bg: st.backgroundColor,
text: bd.textContent,
inside_button: rbd.left >= rb.left && rbd.right <= rb.right && rbd.top >= rb.top && rbd.bottom <= rb.bottom
};
}""")
c4_exp = {
"position": "relative",
"top": "-1px",
"bg": "rgb(248, 249, 250)",
"text": "4",
"inside_button": True,
}
cases = [
{"name": "heading_badge_scaling", "input": "h1-h6 with .badge.badge-secondary", "expected": c1_exp, "actual": c1_actual, "passed": c1_actual == c1_exp},
{"name": "contextual_badge_colors", "input": "8 Bootstrap 4 .badge-* color classes", "expected": c2_exp, "actual": c2_actual, "passed": c2_actual == c2_exp},
{"name": "pill_badges_and_default_note", "input": ".badge-pill vs standard .badge & legacy .badge-default", "expected": c3_exp, "actual": c3_actual, "passed": c3_actual == c3_exp},
{"name": "badge_inside_button", "input": ".btn.btn-primary containing .badge.badge-light", "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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
`.badge` 使用相对单位 `font-size: 75%` 和 `em` 内边距,因此自动按父元素字号按比例缩放;Bootstrap 4 已移除 `.badge-default`,未定义其背景色,需改用 `.badge-secondary` 等标准语义类。