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

Bootstrap5 进度条

核对 Bootstrap 5 进度条基础结构、高度定制、文本标签、语义配色、渐变条纹动画及多段堆叠渲染。

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

学完这一章,你能够

进度条基本结构与高度调整

进度条用于直观反馈任务完成比例。构建基础进度条只需三步:外层 `<div>` 添加 `.progress` 作为浅灰轨道,内部放置 `.progress-bar` 子元素,并通过内联 `style="width: 70%"`(或宽度工具类,并建议配合 `role="progressbar"` 及 `aria-valuenow`)设定完成占比。本站离线 Chromium 在 `500px` 容器内实测默认轨道背景为 `rgb(233, 236, 239)`、高度 `16px`,`70%` 进度条精确渲染为 `350px`。

`.progress` 默认高度为 `16px`(`1rem`),如需加粗或变细,直接在 `.progress` 上通过 CSS `height` 属性覆盖即可,内部 `.progress-bar` 会随弹性容器自动撑满高度。实测设置 `style="height: 20px;"` 后轨道与 `40%` 填充条高度同步变为 `20px`、宽度 `200px`。

进度条标签与语义颜色

直接将百分比或状态文字写入 `.progress-bar` 标签内即可显示进度标签。实测标签文字水平居中(`text-align: center`)、前景白色(`rgb(255, 255, 255)`)且不换行。

进度条默认呈蓝色(`rgb(13, 110, 253)`),可通过 `.bg-success`、`.bg-info`、`.bg-warning`、`.bg-danger` 等背景工具类切换语义色彩。实测 40%/50%/60%/70% 四条彩色进度条在 `500px` 轨道内分别精确计算为 `200px`/`250px`/`300px`/`350px` 并匹配对应 Bootstrap 5 语义色。

条纹样式、动态动画与混合色彩堆叠

在 `.progress-bar` 上追加 `.progress-bar-striped` 可叠加 45 度半透明斜向条纹。实测该元素 `background-image` 包含 `linear-gradient` 且平铺单元 `background-size` 为 `16px 16px`。

在条纹进度条基础上继续添加 `.progress-bar-animated`(注意需位于 `.progress` 外层轨道内),即可通过 CSS 关键帧让条纹持续平移。实测计算样式绑定动画名 `progress-bar-stripes`、周期 `1s`、循环次数 `infinite`。

利用 `.progress` 的弹性行布局,在同一个轨道内并列放入多个 `.progress-bar` 即可组成多段混合色彩进度条(例如空间占用统计)。实测 `40%` 绿 + `10%` 黄 + `20%` 红三段在 `500px` 容器内精确无缝拼接为 `200px`、`50px`、`100px`(总计 `350px`),顶部对齐且零重叠。

在离线 Chromium 中验证进度条高度、标签配色、条纹动画与多段拼接

python · 阅读源码
"""Offline Playwright Chromium verification for Bootstrap 5 Progress Bars (Ch 14)."""
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; }
  .wrap { width: 500px; }
  .progress {
    display: flex;
    height: 1rem;
    overflow: hidden;
    font-size: 0.75rem;
    background-color: #e9ecef;
    border-radius: 0.375rem;
    margin-bottom: 12px;
  }
  .progress-bar {
    display: flex;
    flex-direction: column;
    justify-content: center;
    overflow: hidden;
    color: #fff;
    text-align: center;
    white-space: nowrap;
    background-color: #0d6efd;
  }
  .bg-success { background-color: #198754 !important; }
  .bg-info { background-color: #0dcaf0 !important; }
  .bg-warning { background-color: #ffc107 !important; }
  .bg-danger { background-color: #dc3545 !important; }
  .progress-bar-striped {
    background-image: linear-gradient(
      45deg,
      rgba(255, 255, 255, 0.15) 25%,
      transparent 25%,
      transparent 50%,
      rgba(255, 255, 255, 0.15) 50%,
      rgba(255, 255, 255, 0.15) 75%,
      transparent 75%,
      transparent
    );
    background-size: 1rem 1rem;
  }
  @keyframes progress-bar-stripes {
    0% { background-position-x: 1rem; }
  }
  .progress-bar-animated {
    animation: 1s linear infinite progress-bar-stripes;
  }
</style>
</head>
<body>
<div class="wrap">
  <div id="p-basic" class="progress">
    <div id="pb-basic" class="progress-bar" style="width:70%"></div>
  </div>
  <div id="p-height" class="progress" style="height:20px;">
    <div id="pb-height" class="progress-bar" style="width:40%;"></div>
  </div>
  <div class="progress">
    <div id="pb-label" class="progress-bar" style="width:70%">70%</div>
  </div>
  <div class="progress"><div id="pb-success" class="progress-bar bg-success" style="width:40%"></div></div>
  <div class="progress"><div id="pb-info" class="progress-bar bg-info" style="width:50%"></div></div>
  <div class="progress"><div id="pb-warning" class="progress-bar bg-warning" style="width:60%"></div></div>
  <div class="progress"><div id="pb-danger" class="progress-bar bg-danger" style="width:70%"></div></div>
  <div class="progress">
    <div id="pb-striped" class="progress-bar progress-bar-striped" style="width:40%"></div>
  </div>
  <div class="progress">
    <div id="pb-animated" class="progress-bar progress-bar-striped progress-bar-animated" style="width:40%"></div>
  </div>
  <div id="p-stacked" class="progress">
    <div id="st-free" class="progress-bar bg-success" style="width:40%">Free Space</div>
    <div id="st-warn" class="progress-bar bg-warning" style="width:10%">Warning</div>
    <div id="st-danger" class="progress-bar bg-danger" style="width:20%">Danger</div>
  </div>
</div>
</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": 800, "height": 600})
        page.set_content(HTML, wait_until="load")

        c1_actual = page.evaluate("""() => {
            const pBasic = document.getElementById("p-basic").getBoundingClientRect();
            const pbBasic = document.getElementById("pb-basic").getBoundingClientRect();
            const pH = document.getElementById("p-height").getBoundingClientRect();
            const pbH = document.getElementById("pb-height").getBoundingClientRect();
            return {
                default_track_height_px: Math.round(pBasic.height),
                basic_70pct_width_px: Math.round(pbBasic.width),
                custom_track_height_px: Math.round(pH.height),
                custom_bar_height_px: Math.round(pbH.height),
                custom_40pct_width_px: Math.round(pbH.width),
                track_bg: getComputedStyle(document.getElementById("p-basic")).backgroundColor,
            };
        }""")
        c1_expected = {
            "default_track_height_px": 16,
            "basic_70pct_width_px": 350,
            "custom_track_height_px": 20,
            "custom_bar_height_px": 20,
            "custom_40pct_width_px": 200,
            "track_bg": "rgb(233, 236, 239)",
        }

        c2_actual = page.evaluate("""() => {
            const info = id => {
                const el = document.getElementById(id);
                return { bg: getComputedStyle(el).backgroundColor, w: Math.round(el.getBoundingClientRect().width) };
            };
            const lbl = document.getElementById("pb-label");
            return {
                label_text: lbl.textContent,
                label_color: getComputedStyle(lbl).color,
                label_align: getComputedStyle(lbl).textAlign,
                default_bg: info("pb-basic").bg,
                success: info("pb-success"),
                info: info("pb-info"),
                warning: info("pb-warning"),
                danger: info("pb-danger"),
            };
        }""")
        c2_expected = {
            "label_text": "70%",
            "label_color": "rgb(255, 255, 255)",
            "label_align": "center",
            "default_bg": "rgb(13, 110, 253)",
            "success": {"bg": "rgb(25, 135, 84)", "w": 200},
            "info": {"bg": "rgb(13, 202, 240)", "w": 250},
            "warning": {"bg": "rgb(255, 193, 7)", "w": 300},
            "danger": {"bg": "rgb(220, 53, 69)", "w": 350},
        }

        c3_actual = page.evaluate("""() => {
            const s1 = getComputedStyle(document.getElementById("pb-striped"));
            const s2 = getComputedStyle(document.getElementById("pb-animated"));
            return {
                has_linear_gradient: s1.backgroundImage.includes("linear-gradient"),
                stripe_bg_size: s1.backgroundSize,
                animated_name: s2.animationName,
                animated_duration: s2.animationDuration,
                animated_iteration: s2.animationIterationCount,
            };
        }""")
        c3_expected = {
            "has_linear_gradient": True,
            "stripe_bg_size": "16px 16px",
            "animated_name": "progress-bar-stripes",
            "animated_duration": "1s",
            "animated_iteration": "infinite",
        }

        c4_actual = page.evaluate("""() => {
            const r1 = document.getElementById("st-free").getBoundingClientRect();
            const r2 = document.getElementById("st-warn").getBoundingClientRect();
            const r3 = document.getElementById("st-danger").getBoundingClientRect();
            return {
                widths_px: [Math.round(r1.width), Math.round(r2.width), Math.round(r3.width)],
                contiguous: Math.round(r1.right) === Math.round(r2.left) && Math.round(r2.right) === Math.round(r3.left),
                same_top: Math.round(r1.top) === Math.round(r2.top) && Math.round(r2.top) === Math.round(r3.top),
                total_width_px: Math.round(r1.width + r2.width + r3.width),
            };
        }""")
        c4_expected = {
            "widths_px": [200, 50, 100],
            "contiguous": True,
            "same_top": True,
            "total_width_px": 350,
        }

        browser.close()

    cases = [
        dict(name="basic_progress_and_height", description="核对 .progress 默认 16px 高度、自定义 20px 高度及百分比宽度换算", expected=c1_expected, actual=c1_actual, passed=c1_actual == c1_expected),
        dict(name="labeled_and_contextual_bars", description="核对进度条居中文本标签与默认/success/info/warning/danger 语义色", expected=c2_expected, actual=c2_actual, passed=c2_actual == c2_expected),
        dict(name="striped_and_animated_bars", description="核对 .progress-bar-striped 45 度渐变条纹与 .progress-bar-animated 1s 无限动画", expected=c3_expected, actual=c3_actual, passed=c3_actual == c3_expected),
        dict(name="stacked_multiple_bars", description="核对同一 .progress 弹性容器内多段不同颜色进度条无缝拼接", 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()
预期结果 · 待实际运行核验
  • 核对默认 16px/自定义 20px 高度、70%=350px 等比换算、45 度条纹 1s 无限动画及 40%+10%+20% 无缝拼接 350px。
在离线 Chromium 中验证进度条高度、标签配色、条纹动画与多段拼接

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

当前源码 SHA256:1549fd4bc3c98ce0c1b10344addda49254d9f905adf8093ed30062c5691ced68

下载本站示例源码

本地运行

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

下载Bootstrap5 进度条实验

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

ZIP SHA256:aafc4acf762e1c51357b00a639518b7c460800de80d8137ce89e3dd331f9e39e

常见错误与边界

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

练习与解答

为什么给 `.progress-bar-animated` 单独使用而不加 `.progress-bar-striped` 看不到移动效果?

展开参考解答

`.progress-bar-animated` 通过周期性平移 `background-position-x` 产生动态视觉效果,前提是元素上存在 `.progress-bar-striped` 生成的斜向渐变背景图案。

规范与官方依据