蓝色天空.知识 · 实践 · 创造
我的收藏
Bootstrap5 教程目录 38章
Bootstrap5 / LEARN BY DOING

Bootstrap5 徽章

核对 Bootstrap 5 徽章相对字号缩放、.bg-* 语义配色、.rounded-pill 药丸圆角及按钮内嵌计数展示。

学完这一章,你能够

  • 核对 Bootstrap 5 徽章相对字号缩放、.bg-* 语义配色、.rounded-pill 药丸圆角及按钮内嵌计数展示。

徽章基础用法与父级字号缩放

徽章(Badges)常用于标识新增内容、状态标签或未读计数。Bootstrap 5 中在 `<span>` 上组合 `.badge` 与背景色工具类(如 `.bg-secondary`,取代 Bootstrap 4 的 `.badge-*` 写法)即可生成徽章;其字号采用相对单位 `0.75em`,因此会自动随父级标题 `<h1>`–`<h6>` 等比缩放。本站离线 Chromium 实测在 16px 根字号下,`h1`–`h6` 内的 `.badge` 计算字号依次为 `30px`、`24px`、`21px`、`18px`、`15px`、`12px`,呈严格递减。

语义颜色与药丸圆角(BS5 变更)

Bootstrap 5 复用通用背景工具类 `.bg-primary`、`.bg-secondary`、`.bg-success`、`.bg-danger`、`.bg-warning`、`.bg-info`、`.bg-light`、`.bg-dark` 控制徽章配色;对于浅底色(如 `.bg-light`、`.bg-warning`、`.bg-info`),需搭配 `.text-dark` 或 Bootstrap 5.2+ 的 `.text-bg-*` 以保证对比度。实测 8 种语义背景色均精确匹配官方色值,且 `.bg-light.text-dark` 文字为 `rgb(33, 37, 41)`。

Bootstrap 5 移除了 Bootstrap 4 的 `.badge-pill`,改为叠加通用圆角工具类 `.rounded-pill` 生成两端半圆形的药丸徽章。实测默认 `.badge` 圆角为 `6px`(`0.375rem`),叠加 `.rounded-pill` 后计算圆角变为 `800px`(`50rem`)。

徽章嵌入按钮与交互元件

徽章可直接内嵌于 `<button>` 或导航链接中充当未读消息计数器(如 `<button class="btn btn-primary">Messages <span class="badge bg-light text-dark">4</span></button>`)。实测内嵌徽章保持 `display: inline-block`、`12px` 字号,并完整落于按钮包围盒之内。

在离线 Chromium 中验证 h1-h6 徽章缩放、8 种 bg-* 配色、rounded-pill 及按钮内嵌计数

含完整源码 · 185 行
展开查看收起
python
"""Offline Playwright Chromium verification for Bootstrap 5 Badges (Ch 13)."""
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; }
  h1 { font-size: 2.5rem; margin: 4px 0; }
  h2 { font-size: 2rem; margin: 4px 0; }
  h3 { font-size: 1.75rem; margin: 4px 0; }
  h4 { font-size: 1.5rem; margin: 4px 0; }
  h5 { font-size: 1.25rem; margin: 4px 0; }
  h6 { font-size: 1rem; margin: 4px 0; }
  .badge {
    display: inline-block;
    padding: 0.35em 0.65em;
    font-size: 0.75em;
    font-weight: 700;
    line-height: 1;
    color: #fff;
    text-align: center;
    white-space: nowrap;
    vertical-align: baseline;
    border-radius: 0.375rem;
  }
  .rounded-pill { border-radius: 50rem !important; }
  .bg-primary { background-color: #0d6efd !important; }
  .bg-secondary { background-color: #6c757d !important; }
  .bg-success { background-color: #198754 !important; }
  .bg-danger { background-color: #dc3545 !important; }
  .bg-warning { background-color: #ffc107 !important; }
  .bg-info { background-color: #0dcaf0 !important; }
  .bg-light { background-color: #f8f9fa !important; }
  .bg-dark { background-color: #212529 !important; }
  .text-dark { color: #212529 !important; }
  .btn {
    display: inline-block; padding: 0.375rem 0.75rem; font-size: 1rem; line-height: 1.5;
    border: 1px solid transparent; border-radius: 0.375rem;
  }
  .btn-primary { color: #fff; background-color: #0d6efd; border-color: #0d6efd; }
</style>
</head>
<body>
<section id="sec-headings">
  <h1>测试标题 <span id="bh1" class="badge bg-secondary">New</span></h1>
  <h2>测试标题 <span id="bh2" class="badge bg-secondary">New</span></h2>
  <h3>测试标题 <span id="bh3" class="badge bg-secondary">New</span></h3>
  <h4>测试标题 <span id="bh4" class="badge bg-secondary">New</span></h4>
  <h5>测试标题 <span id="bh5" class="badge bg-secondary">New</span></h5>
  <h6>测试标题 <span id="bh6" class="badge bg-secondary">New</span></h6>
</section>

<section id="sec-colors">
  <span id="c-primary" class="badge bg-primary">主要</span>
  <span id="c-secondary" class="badge bg-secondary">次要</span>
  <span id="c-success" class="badge bg-success">成功</span>
  <span id="c-danger" class="badge bg-danger">危险</span>
  <span id="c-warning" class="badge bg-warning text-dark">警告</span>
  <span id="c-info" class="badge bg-info text-dark">信息</span>
  <span id="c-light" class="badge bg-light text-dark">浅色</span>
  <span id="c-dark" class="badge bg-dark">深色</span>
</section>

<section id="sec-pills">
  <span id="p-primary" class="badge rounded-pill bg-primary">主要</span>
  <span id="p-success" class="badge rounded-pill bg-success">成功</span>
  <span id="p-info" class="badge rounded-pill bg-info text-dark">信息</span>
  <span id="p-warning" class="badge rounded-pill bg-warning text-dark">警告</span>
  <span id="p-danger" class="badge rounded-pill bg-danger">危险</span>
</section>

<section id="sec-btn">
  <button id="msg-btn" type="button" class="btn btn-primary">
    Messages <span id="msg-badge" class="badge bg-light text-dark">4</span>
  </button>
</section>
</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": 900, "height": 700})
        page.set_content(HTML, wait_until="load")

        c1_actual = page.evaluate("""() => {
            const ids = ["bh1", "bh2", "bh3", "bh4", "bh5", "bh6"];
            const px = ids.map(id => parseFloat(getComputedStyle(document.getElementById(id)).fontSize));
            let decreasing = true;
            for (let i = 1; i < px.length; i++) if (!(px[i - 1] > px[i])) decreasing = false;
            return {
                badge_font_sizes_px: px,
                strictly_decreasing: decreasing,
            };
        }""")
        c1_expected = {
            "badge_font_sizes_px": [30.0, 24.0, 21.0, 18.0, 15.0, 12.0],
            "strictly_decreasing": True,
        }

        c2_actual = page.evaluate("""() => {
            const bg = id => getComputedStyle(document.getElementById(id)).backgroundColor;
            return {
                primary: bg("c-primary"),
                secondary: bg("c-secondary"),
                success: bg("c-success"),
                danger: bg("c-danger"),
                warning: bg("c-warning"),
                info: bg("c-info"),
                light: bg("c-light"),
                dark: bg("c-dark"),
                light_text_color: getComputedStyle(document.getElementById("c-light")).color,
            };
        }""")
        c2_expected = {
            "primary": "rgb(13, 110, 253)",
            "secondary": "rgb(108, 117, 125)",
            "success": "rgb(25, 135, 84)",
            "danger": "rgb(220, 53, 69)",
            "warning": "rgb(255, 193, 7)",
            "info": "rgb(13, 202, 240)",
            "light": "rgb(248, 249, 250)",
            "dark": "rgb(33, 37, 41)",
            "light_text_color": "rgb(33, 37, 41)",
        }

        c3_actual = page.evaluate("""() => {
            const defR = getComputedStyle(document.getElementById("c-primary")).borderTopLeftRadius;
            const pillR = getComputedStyle(document.getElementById("p-primary")).borderTopLeftRadius;
            const allPills = ["p-primary", "p-success", "p-info", "p-warning", "p-danger"]
                .every(id => getComputedStyle(document.getElementById(id)).borderTopLeftRadius === "800px");
            return { default_radius: defR, pill_radius: pillR, all_five_pills_800px: allPills };
        }""")
        c3_expected = {
            "default_radius": "6px",
            "pill_radius": "800px",
            "all_five_pills_800px": True,
        }

        c4_actual = page.evaluate("""() => {
            const btn = document.getElementById("msg-btn").getBoundingClientRect();
            const bdg = document.getElementById("msg-badge").getBoundingClientRect();
            const s = getComputedStyle(document.getElementById("msg-badge"));
            return {
                display: s.display,
                text: document.getElementById("msg-badge").textContent,
                contained_inside_button: bdg.left >= btn.left && bdg.right <= btn.right && bdg.top >= btn.top && bdg.bottom <= btn.bottom,
                font_size: s.fontSize,
            };
        }""")
        c4_expected = {
            "display": "inline-block",
            "text": "4",
            "contained_inside_button": True,
            "font_size": "12px",
        }

        browser.close()

    cases = [
        dict(name="heading_relative_scaling", description="核对 .badge 的 0.75em 相对字号在 h1-h6 中逐级缩放", expected=c1_expected, actual=c1_actual, passed=c1_actual == c1_expected),
        dict(name="contextual_bg_colors", description="核对 BS5 .badge.bg-* 8 种语义背景色与浅色背景文字对比度", expected=c2_expected, actual=c2_actual, passed=c2_actual == c2_expected),
        dict(name="rounded_pill_badges", description="核对 BS5 .rounded-pill (50rem=800px) 与默认 6px 圆角差异", expected=c3_expected, actual=c3_actual, passed=c3_actual == c3_expected),
        dict(name="badge_inside_button", description="核对按钮内嵌徽章的 inline-block 定位与 12px 相对字号", 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()
核对 h1-h6 内徽章字号依次为 30/24/21/18/15/12px、8 种 bg-* 色值、rounded-pill 圆角 800px 及按钮内 12px 徽章边界包含。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a701.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Bootstrap5

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a701.zip

下载课程关联工程包:Bootstrap5

课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a700.zip

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

应改写为 `<span class="badge rounded-pill bg-success">`(Bootstrap 5.2+ 亦可用 `<span class="badge rounded-pill text-bg-success">` 自动匹配前景文字对比色)。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习