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

Bootstrap5 小工具

核对 Bootstrap 5 常用工具类:背景色与渐变、边框与圆角、逻辑方向浮动与清除浮动、居中与宽高比例,以及完整响应式间距语法体系。

学完这一章,你能够

  • 核对 Bootstrap 5 常用工具类:背景色与渐变、边框与圆角、逻辑方向浮动与清除浮动、居中与宽高比例,以及完整响应式间距语法体系。

背景色、渐变、边框与圆角工具类

Bootstrap 5 提供一整套原子化工具类以减少重复手写 CSS。背景色涵盖 `.bg-primary`、`.bg-secondary`、`.bg-success`、`.bg-danger`、`.bg-warning`、`.bg-info`、`.bg-light`、`.bg-dark`、`.bg-body`、`.bg-white` 与 `.bg-transparent`,使用时应搭配高对比度文字类(如 `.text-white` 或 `.text-dark`);叠加 `.bg-gradient` 可附加自顶向下的半透明线性渐变。离线 Chromium 实测 `.bg-primary` 为 `rgb(13, 110, 253)`、`.bg-warning` 为 `rgb(255, 193, 7)`、`.bg-transparent` 为 `rgba(0, 0, 0, 0)`,`.bg-gradient` 具备 `linear-gradient` 背景图。

边框工具类支持增减单边(`.border`、`.border-top|end|bottom|start` 与 `.border-0`、`.border-top-0|end-0|bottom-0|start-0`)、调节线宽(`.border-1` 至 `.border-5` 对应 `1px` 至 `5px`)以及指定主题边框色(`.border-primary` 至 `.border-white`)。实测 `.border.border-top-0` 顶边为 `0px` 而底边维持 `1px`,`.border-end` 仅右边为 `1px`,`.border-5.border-danger` 测得 `5px` 与 `rgb(220, 53, 69)`。

圆角控制使用 `.rounded`(`4px`)、单侧圆角 `.rounded-top|end|bottom|start`、正圆 `.rounded-circle`(`50%`)、胶囊形 `.rounded-pill`(`50rem`,实测 `800px`)以及四档圆角尺寸 `.rounded-0` 至 `.rounded-3`(实测 `.rounded-0` 为 `0px`、`.rounded-3` 为 `4.8px`)。上述背景色条、五种边框与七种圆角形态均已结合缓存参考图完成核对(私有留证)。

逻辑浮动、居中对齐、宽高与比例控制

Bootstrap 5 采用书写方向无关的逻辑浮动类:`.float-start` 向左浮动(`float: left`)、`.float-end` 向右浮动(`float: right`)、`.float-none` 取消浮动,父容器用 `.clearfix` 清除内部浮动塌陷(实测包含 `36px` 浮动子项时容器高度稳定保持 `36px`)。响应式断点类遵循 `.float-{sm|md|lg|xl|xxl}-{start|end|none}`(注意 Bootstrap 5 已以 `start`/`end` 替代旧版 `left`/`right`),实测 `.float-md-end` 在 `500px` 视口为 `none`,在 `900px` 视口切为 `right`。对定宽块级元素添加 `.mx-auto` 可自动分配左右外边距实现水平居中(实测 `800px` 容器内 `150px` 盒子左右边距精确为 `325px`)。

相对父容器的宽度类为 `.w-25`、`.w-50`、`.w-75`、`.w-100`、`.w-auto` 与最大宽度 `.mw-100`,高度类为 `.h-25`、`.h-50`、`.h-75`、`.h-100`、`.h-auto` 与最大高度 `.mh-100`(注:标准自动宽高类为 `.w-auto`/`.h-auto`,而非 `.mw-auto`/`.mh-auto`)。离线 Chromium 实测 `800px` 宽容器内 `.w-25/.w-50/.w-75/.w-100/.mw-100` 实际宽度依次为 `[200, 400, 600, 800, 800]` 像素,`200px` 高容器内 `.h-25/.h-50/.h-100/.mh-100` 实际高度为 `[50, 100, 200, 200]` 像素(`.mh-100` 将 `500px` 子块截断在 `200px`);同时实测 Bootstrap 5 常用 `.ratio.ratio-16x9` 在 `320px` 宽下精确形成 `320×180` 宽高比。

响应式间距语法与方向速查表

间距工具类采用统一命名语法 `{property}{sides}-{size}`(适用全视口/`xs`)与 `{property}{sides}-{breakpoint}-{size}`(断点 `sm>=576px`、`md>=768px`、`lg>=992px`、`xl>=1200px`、`xxl>=1400px`)。其中 `property` 取 `m`(margin)或 `p`(padding);`sides` 取 `t`(顶)、`b`(底)、`s`(逻辑起边,LTR 为左)、`e`(逻辑终边,LTR 为右)、`x`(左右双边)、`y`(上下双边)或留空(四边同时生效)。

尺寸等级 `size` 基于基准变量 `$spacer`(默认 `1rem = 16px`)换算:`0` 为 `0px`、`1` 为 `0.25rem (4px)`、`2` 为 `0.5rem (8px)`、`3` 为 `1rem (16px)`、`4` 为 `1.5rem (24px)`、`5` 为 `3rem (48px)`,外边距还支持 `auto`。注意 Bootstrap 5 中左侧外边距类为 `.ms-1`(替代旧版 `.ml-1`),常与表单标签 `.mt-2` 及居中容器 `.mx-auto` 配合使用。离线 Chromium 实测 `.m-0` 至 `.m-5` 计算值精确为 `["0px", "4px", "8px", "16px", "24px", "48px"]`,响应式 `.ms-md-4` 在 `500px` 下为 `0px`、在 `900px` 下为 `24px`。下表汇总了全部 14 组间距类映射。

Bootstrap 5 外边距与内边距工具类速查

类语法对应 CSS 方向与说明
.m-# / m-*-#设置四边外边距 `margin`(实测 `m-0..m-5` 对应 `0..48px`)
.mt-# / mt-*-#设置顶部外边距 `margin-top`(实测 `mt-2` 为 `8px`)
.mb-# / mb-*-#设置底部外边距 `margin-bottom`(实测 `mb-3` 为 `16px`)
.ms-# / ms-*-#设置逻辑起始边外边距(LTR 为 `margin-left`,实测 `ms-1=4px`、`ms-md-4` 断点生效 `24px`)
.me-# / me-*-#设置逻辑结束边外边距(LTR 为 `margin-right`,实测 `me-4` 为 `24px`)
.mx-# / mx-*-#同时设置左右外边距 `margin-left` 与 `margin-right`(含 `mx-auto` 居中)
.my-# / my-*-#同时设置上下外边距 `margin-top` 与 `margin-bottom`(实测 `my-2` 各为 `8px`)
.p-# / p-*-#设置四边内边距 `padding`(按 `$spacer` 阶梯缩放)
.pt-# / pt-*-#设置顶部内边距 `padding-top`(实测 `pt-1` 为 `4px`)
.pb-# / pb-*-#设置底部内边距 `padding-bottom`(实测 `pb-2` 为 `8px`)
.ps-# / ps-*-#设置逻辑起始边内边距(LTR 为 `padding-left`,实测 `ps-4` 为 `24px`)
.pe-# / pe-*-#设置逻辑结束边内边距(LTR 为 `padding-right`,实测 `pe-5` 为 `48px`)
.py-# / py-*-#同时设置上下内边距 `padding-top` 与 `padding-bottom`(实测 `py-3` 各为 `16px`)
.px-# / px-*-#同时设置左右内边距 `padding-left` 与 `padding-right`(实测 `px-2` 各为 `8px`)

离线 Chromium 核验 Bootstrap 5 背景、边框圆角、逻辑浮动、宽高与响应式间距

含完整源码 · 314 行
展开查看收起
python
"""Offline Playwright Chromium verification for Bootstrap 5 Utilities (Ch 30)."""
import json
from playwright.sync_api import sync_playwright

BS5_UTIL_CSS = """
:root { --bs-gradient: linear-gradient(180deg, rgba(255,255,255,0.15), rgba(255,255,255,0)); }
* { box-sizing: border-box; }
html { font-size: 16px; }
body { margin: 0; font-family: system-ui, sans-serif; }
.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; }
.bg-body { background-color: #fff !important; }
.bg-white { background-color: #fff !important; }
.bg-transparent { background-color: transparent !important; }
.bg-gradient { background-image: var(--bs-gradient) !important; }
.text-white { color: #fff !important; }
.text-dark { color: #212529 !important; }

.border { border: 1px solid #dee2e6 !important; }
.border-0 { border: 0 !important; }
.border-top { border-top: 1px solid #dee2e6 !important; }
.border-end { border-right: 1px solid #dee2e6 !important; }
.border-bottom { border-bottom: 1px solid #dee2e6 !important; }
.border-start { border-left: 1px solid #dee2e6 !important; }
.border-top-0 { border-top: 0 !important; }
.border-end-0 { border-right: 0 !important; }
.border-bottom-0 { border-bottom: 0 !important; }
.border-start-0 { border-left: 0 !important; }
.border-1 { border-width: 1px !important; }
.border-2 { border-width: 2px !important; }
.border-3 { border-width: 3px !important; }
.border-4 { border-width: 4px !important; }
.border-5 { border-width: 5px !important; }
.border-primary { border-color: #0d6efd !important; }
.border-danger { border-color: #dc3545 !important; }

.rounded { border-radius: 0.25rem !important; }
.rounded-top { border-top-left-radius: 0.25rem !important; border-top-right-radius: 0.25rem !important; }
.rounded-end { border-top-right-radius: 0.25rem !important; border-bottom-right-radius: 0.25rem !important; }
.rounded-bottom { border-bottom-right-radius: 0.25rem !important; border-bottom-left-radius: 0.25rem !important; }
.rounded-start { border-bottom-left-radius: 0.25rem !important; border-top-left-radius: 0.25rem !important; }
.rounded-circle { border-radius: 50% !important; }
.rounded-pill { border-radius: 50rem !important; }
.rounded-0 { border-radius: 0 !important; }
.rounded-1 { border-radius: 0.2rem !important; }
.rounded-2 { border-radius: 0.25rem !important; }
.rounded-3 { border-radius: 0.3rem !important; }

.float-start { float: left !important; }
.float-end { float: right !important; }
.float-none { float: none !important; }
@media (min-width: 768px) { .float-md-end { float: right !important; } }
.clearfix::after { display: block; clear: both; content: ""; }

.w-25 { width: 25% !important; }
.w-50 { width: 50% !important; }
.w-75 { width: 75% !important; }
.w-100 { width: 100% !important; }
.w-auto { width: auto !important; }
.mw-100 { max-width: 100% !important; }
.h-25 { height: 25% !important; }
.h-50 { height: 50% !important; }
.h-75 { height: 75% !important; }
.h-100 { height: 100% !important; }
.h-auto { height: auto !important; }
.mh-100 { max-height: 100% !important; }
.d-inline-block { display: inline-block !important; }

.ratio { position: relative; width: 100%; }
.ratio::before { display: block; padding-top: var(--bs-aspect-ratio); content: ""; }
.ratio-16x9 { --bs-aspect-ratio: calc(9 / 16 * 100%); }

/* Spacing ($spacer = 1rem = 16px) */
.m-0 { margin: 0 !important; }
.m-1 { margin: 0.25rem !important; }
.m-2 { margin: 0.5rem !important; }
.m-3 { margin: 1rem !important; }
.m-4 { margin: 1.5rem !important; }
.m-5 { margin: 3rem !important; }
.mt-2 { margin-top: 0.5rem !important; }
.mb-3 { margin-bottom: 1rem !important; }
.ms-1 { margin-left: 0.25rem !important; }
.me-4 { margin-right: 1.5rem !important; }
.mx-auto { margin-right: auto !important; margin-left: auto !important; }
.my-2 { margin-top: 0.5rem !important; margin-bottom: 0.5rem !important; }
.p-0 { padding: 0 !important; }
.p-3 { padding: 1rem !important; }
.pt-1 { padding-top: 0.25rem !important; }
.pb-2 { padding-bottom: 0.5rem !important; }
.ps-4 { padding-left: 1.5rem !important; }
.pe-5 { padding-right: 3rem !important; }
.px-2 { padding-right: 0.5rem !important; padding-left: 0.5rem !important; }
.py-3 { padding-top: 1rem !important; padding-bottom: 1rem !important; }
@media (min-width: 768px) { .ms-md-4 { margin-left: 1.5rem !important; } }
"""

HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{BS5_UTIL_CSS}</style></head>
<body>
  <div id="bg-primary" class="p-3 bg-primary text-white">Primary</div>
  <div id="bg-warning" class="p-3 bg-warning text-dark">Warning</div>
  <div id="bg-transparent" class="p-3 bg-transparent text-dark">Transparent</div>
  <div id="bg-grad" class="p-3 bg-primary bg-gradient text-white">Gradient</div>

  <div id="bd-all" class="border"></div>
  <div id="bd-top0" class="border border-top-0"></div>
  <div id="bd-end-only" class="border-end"></div>
  <div id="bd-w5" class="border border-5 border-danger"></div>
  <div id="rd-base" class="rounded" style="width:75px;height:75px;"></div>
  <div id="rd-circle" class="rounded-circle" style="width:75px;height:75px;"></div>
  <div id="rd-pill" class="rounded-pill" style="width:150px;height:75px;"></div>
  <div id="rd-0" class="rounded-0" style="width:50px;height:50px;"></div>
  <div id="rd-3" class="rounded-3" style="width:50px;height:50px;"></div>

  <div id="cf-box" class="clearfix" style="width:800px;">
    <span id="fl-start" class="float-start" style="height:36px;">Left</span>
    <span id="fl-end" class="float-end" style="height:36px;">Right</span>
  </div>
  <div id="fl-md" class="float-md-end">RespFloat</div>

  <div id="center-wrap" style="width:800px;">
    <div id="center-box" class="mx-auto bg-warning" style="width:150px;">Center</div>
  </div>

  <div id="w-wrap" style="width:800px;">
    <div id="w25" class="w-25">25%</div>
    <div id="w50" class="w-50">50%</div>
    <div id="w75" class="w-75">75%</div>
    <div id="w100" class="w-100">100%</div>
    <div id="mw100" class="mw-100" style="width:1200px;">MW100</div>
  </div>

  <div id="h-wrap" style="height:200px;width:600px;">
    <div id="h25" class="h-25 d-inline-block">25%</div>
    <div id="h50" class="h-50 d-inline-block">50%</div>
    <div id="h100" class="h-100 d-inline-block">100%</div>
    <div id="mh100" class="mh-100 d-inline-block" style="height:500px;">MH100</div>
  </div>

  <div style="width:320px;"><div id="ratio169" class="ratio ratio-16x9"></div></div>

  <div id="sp-m0" class="m-0"></div>
  <div id="sp-m1" class="m-1"></div>
  <div id="sp-m2" class="m-2"></div>
  <div id="sp-m3" class="m-3"></div>
  <div id="sp-m4" class="m-4"></div>
  <div id="sp-m5" class="m-5"></div>
  <div id="sp-dirs-m" class="mt-2 mb-3 ms-1 me-4"></div>
  <div id="sp-dirs-p" class="pt-1 pb-2 ps-4 pe-5"></div>
  <div id="sp-xy" class="px-2 py-3 my-2"></div>
  <div id="sp-resp" class="ms-md-4"></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():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 900, "height": 800})
        page.set_content(HTML_DOC)

        # Case 1: backgrounds & gradient
        c1_actual = page.evaluate("""() => ({
            primary_bg: getComputedStyle(document.querySelector('#bg-primary')).backgroundColor,
            primary_text: getComputedStyle(document.querySelector('#bg-primary')).color,
            warning_bg: getComputedStyle(document.querySelector('#bg-warning')).backgroundColor,
            warning_text: getComputedStyle(document.querySelector('#bg-warning')).color,
            transparent_bg: getComputedStyle(document.querySelector('#bg-transparent')).backgroundColor,
            gradient_has_linear: getComputedStyle(document.querySelector('#bg-grad')).backgroundImage.includes('linear-gradient'),
        })""")
        c1_expected = {
            "primary_bg": "rgb(13, 110, 253)",
            "primary_text": "rgb(255, 255, 255)",
            "warning_bg": "rgb(255, 193, 7)",
            "warning_text": "rgb(33, 37, 41)",
            "transparent_bg": "rgba(0, 0, 0, 0)",
            "gradient_has_linear": True,
        }
        cases.append({
            "name": "utilities_background_and_gradient",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        })

        # Case 2: borders & rounded radii
        c2_actual = page.evaluate("""() => ({
            border_all: getComputedStyle(document.querySelector('#bd-all')).borderTopWidth,
            border_top_0: getComputedStyle(document.querySelector('#bd-top0')).borderTopWidth,
            border_top_0_bottom: getComputedStyle(document.querySelector('#bd-top0')).borderBottomWidth,
            border_end_right: getComputedStyle(document.querySelector('#bd-end-only')).borderRightWidth,
            border_end_left: getComputedStyle(document.querySelector('#bd-end-only')).borderLeftWidth,
            border_5_width: getComputedStyle(document.querySelector('#bd-w5')).borderTopWidth,
            border_danger_color: getComputedStyle(document.querySelector('#bd-w5')).borderTopColor,
            rounded_base: getComputedStyle(document.querySelector('#rd-base')).borderTopLeftRadius,
            rounded_circle: getComputedStyle(document.querySelector('#rd-circle')).borderTopLeftRadius,
            rounded_pill: getComputedStyle(document.querySelector('#rd-pill')).borderTopLeftRadius,
            rounded_0: getComputedStyle(document.querySelector('#rd-0')).borderTopLeftRadius,
            rounded_3: getComputedStyle(document.querySelector('#rd-3')).borderTopLeftRadius,
        })""")
        c2_expected = {
            "border_all": "1px",
            "border_top_0": "0px",
            "border_top_0_bottom": "1px",
            "border_end_right": "1px",
            "border_end_left": "0px",
            "border_5_width": "5px",
            "border_danger_color": "rgb(220, 53, 69)",
            "rounded_base": "4px",
            "rounded_circle": "50%",
            "rounded_pill": "800px",
            "rounded_0": "0px",
            "rounded_3": "4.8px",
        }
        cases.append({
            "name": "utilities_borders_and_rounded",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        })

        # Case 3: float, clearfix, responsive float, mx-auto, width/height & ratio-16x9
        wide_vals = page.evaluate("""() => {
            const c = getComputedStyle(document.querySelector('#center-box'));
            const r = document.querySelector('#ratio169').getBoundingClientRect();
            return {
                float_start: getComputedStyle(document.querySelector('#fl-start')).float,
                float_end: getComputedStyle(document.querySelector('#fl-end')).float,
                clearfix_height: Math.round(document.querySelector('#cf-box').getBoundingClientRect().height),
                float_md_at_900: getComputedStyle(document.querySelector('#fl-md')).float,
                center_ml: c.marginLeft,
                center_mr: c.marginRight,
                widths: ['#w25', '#w50', '#w75', '#w100', '#mw100'].map(s => Math.round(document.querySelector(s).getBoundingClientRect().width)),
                heights: ['#h25', '#h50', '#h100', '#mh100'].map(s => Math.round(document.querySelector(s).getBoundingClientRect().height)),
                ratio_16x9_dims: [Math.round(r.width), Math.round(r.height)],
            };
        }""")
        page.set_viewport_size({"width": 500, "height": 800})
        narrow_float = page.eval_on_selector("#fl-md", "el => getComputedStyle(el).float")
        c3_actual = {**wide_vals, "float_md_at_500": narrow_float}
        c3_expected = {
            "float_start": "left",
            "float_end": "right",
            "clearfix_height": 36,
            "float_md_at_900": "right",
            "center_ml": "325px",
            "center_mr": "325px",
            "widths": [200, 400, 600, 800, 800],
            "heights": [50, 100, 200, 200],
            "ratio_16x9_dims": [320, 180],
            "float_md_at_500": "none",
        }
        cases.append({
            "name": "utilities_float_clearfix_center_and_sizing",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        })

        # Case 4: spacing scale (0..5), directions, and responsive breakpoint spacing
        ms_at_500 = page.eval_on_selector("#sp-resp", "el => getComputedStyle(el).marginLeft")
        page.set_viewport_size({"width": 900, "height": 800})
        c4_actual = page.evaluate("""ms500 => {
            const dm = getComputedStyle(document.querySelector('#sp-dirs-m'));
            const dp = getComputedStyle(document.querySelector('#sp-dirs-p'));
            const xy = getComputedStyle(document.querySelector('#sp-xy'));
            return {
                scale_0_to_5: ['#sp-m0', '#sp-m1', '#sp-m2', '#sp-m3', '#sp-m4', '#sp-m5'].map(s => getComputedStyle(document.querySelector(s)).marginTop),
                margin_sides: [dm.marginTop, dm.marginBottom, dm.marginLeft, dm.marginRight],
                padding_sides: [dp.paddingTop, dp.paddingBottom, dp.paddingLeft, dp.paddingRight],
                px_py_my: [xy.paddingLeft, xy.paddingRight, xy.paddingTop, xy.paddingBottom, xy.marginTop, xy.marginBottom],
                ms_md_4_at_500: ms500,
                ms_md_4_at_900: getComputedStyle(document.querySelector('#sp-resp')).marginLeft,
            };
        }""", ms_at_500)
        c4_expected = {
            "scale_0_to_5": ["0px", "4px", "8px", "16px", "24px", "48px"],
            "margin_sides": ["8px", "16px", "4px", "24px"],
            "padding_sides": ["4px", "8px", "24px", "48px"],
            "px_py_my": ["8px", "8px", "16px", "16px", "8px", "8px"],
            "ms_md_4_at_500": "0px",
            "ms_md_4_at_900": "24px",
        }
        cases.append({
            "name": "utilities_spacing_scale_and_directions",
            "expected": c4_expected,
            "actual": c4_actual,
            "passed": c4_actual == c4_expected,
        })

        browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
核对背景色与 linear-gradient 渐变、单边/线宽/圆角计算像素、.float-start/.float-end/.clearfix/.mx-auto、宽高与 ratio-16x9 以及 0..5 间距标尺和断点切换。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:Bootstrap5

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

下载课程关联工程包:Bootstrap5

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

Bootstrap 5 引入了原生 RTL(从右到左排版)支持,逻辑方向 `start`/`end` 能在 LTR 页面映射为左/右并在 RTL 页面自动翻转,避免硬编码物理左右方向导致镜像排版错乱。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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