蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线验证 Bootstrap 4 12 列 Flexbox 网格、多断点切换与列偏移

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-grid-basic.py
explore-grid-basic.py264 行
"""Offline Playwright Chromium lab for Bootstrap 4 Ch 03 (grid-basic)."""
import json
from playwright.sync_api import sync_playwright


def build_grid_css():
    lines = [
        "*, *::before, *::after { box-sizing: border-box; }",
        "body { margin: 0; font-family: sans-serif; font-size: 16px; }",
        ".container, .container-fluid { width: 100%; padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; }",
        "@media (min-width: 576px) { .container { max-width: 540px; } }",
        "@media (min-width: 768px) { .container { max-width: 720px; } }",
        "@media (min-width: 992px) { .container { max-width: 960px; } }",
        "@media (min-width: 1200px) { .container { max-width: 1140px; } }",
        ".row { display: flex; flex-wrap: wrap; margin-right: -15px; margin-left: -15px; }",
        "[class*='col'] { position: relative; width: 100%; padding-right: 15px; padding-left: 15px; }",
        ".col { flex-basis: 0; flex-grow: 1; max-width: 100%; }",
    ]
    for n in range(1, 13):
        pct = f"{n * 100 / 12:.6f}%"
        lines.append(f".col-{n} {{ flex: 0 0 {pct}; max-width: {pct}; }}")
    for bp, px in (("sm", 576), ("md", 768), ("lg", 992), ("xl", 1200)):
        rules = [f".col-{bp} {{ flex-basis: 0; flex-grow: 1; max-width: 100%; }}"]
        for n in range(1, 13):
            pct = f"{n * 100 / 12:.6f}%"
            rules.append(f".col-{bp}-{n} {{ flex: 0 0 {pct}; max-width: {pct}; }}")
        for n in range(1, 12):
            pct = f"{n * 100 / 12:.6f}%"
            rules.append(f".offset-{bp}-{n} {{ margin-left: {pct}; }}")
        lines.append(f"@media (min-width: {px}px) {{ " + " ".join(rules) + " }")
    return "\n".join(lines)


HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{build_grid_css()}</style></head>
<body>
  <div id="std-container" class="container">
    <div id="nested-outer-row" class="row">
      <div class="col-md-6" id="nested-col">
        <div class="row" id="nested-inner-row">
          <div class="col-6" id="n1">嵌套左</div>
          <div class="col-6" id="n2">嵌套右</div>
        </div>
      </div>
      <div class="col-md-6" id="nested-sib">右侧</div>
    </div>
  </div>

  <div class="container-fluid">
    <div class="row" id="auto2"><div class="col">A</div><div class="col">B</div></div>
    <div class="row" id="auto3"><div class="col">A<br>B<br>C</div><div class="col">B</div><div class="col">C</div></div>
    <div class="row" id="auto4"><div class="col">1</div><div class="col">2</div><div class="col">3</div><div class="col">4</div></div>

    <div class="row" id="sm-eq">
      <div class="col-sm-3">1</div><div class="col-sm-3">2</div>
      <div class="col-sm-3">3</div><div class="col-sm-3">4</div>
    </div>
    <div class="row" id="sm-uneq">
      <div class="col-sm-4">4</div><div class="col-sm-8">8</div>
    </div>
    <div class="row" id="multi-bp">
      <div id="mb-left" class="col-sm-3 col-md-6 col-lg-4 col-xl-2">左栏</div>
      <div id="mb-right" class="col-sm-9 col-md-6 col-lg-8 col-xl-10">右栏</div>
    </div>
  </div>

  <div id="offset-container" class="container">
    <div class="row" id="off-r1">
      <div class="col-md-4" id="o1a">A</div>
      <div class="col-md-4 offset-md-4" id="o1b">B</div>
    </div>
    <div class="row" id="off-r2">
      <div class="col-md-3 offset-md-3" id="o2a">A</div>
      <div class="col-md-3 offset-md-3" id="o2b">B</div>
    </div>
    <div class="row" id="off-r3">
      <div class="col-md-6 offset-md-3" id="o3a">Center</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():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 992, "height": 900})
        page.set_content(HTML_PAGE)

        # Case 1: grid_breakpoints_gutters_and_nesting
        bp = {}
        for vw in (375, 576, 768, 992, 1200):
            page.set_viewport_size({"width": vw, "height": 900})
            bp[str(vw)] = page.evaluate("() => Math.round(document.getElementById('std-container').getBoundingClientRect().width)")
        page.set_viewport_size({"width": 992, "height": 900})
        gutter_nest = page.evaluate("""() => {
            const rs = getComputedStyle(document.getElementById('nested-outer-row'));
            const cs = getComputedStyle(document.getElementById('nested-col'));
            const n1 = document.getElementById('n1').getBoundingClientRect();
            const n2 = document.getElementById('n2').getBoundingClientRect();
            return {
                row_display: rs.display,
                row_margin_x: [parseFloat(rs.marginLeft), parseFloat(rs.marginRight)],
                col_padding_x: [parseFloat(cs.paddingLeft), parseFloat(cs.paddingRight)],
                nested_widths: [Math.round(n1.width), Math.round(n2.width)],
                nested_same_row: Math.round(n1.top) === Math.round(n2.top),
            };
        }""")
        actual_1 = {"container_widths": bp, **gutter_nest}
        expected_1 = {
            "container_widths": {"375": 375, "576": 540, "768": 720, "992": 960, "1200": 1140},
            "row_display": "flex",
            "row_margin_x": [-15.0, -15.0],
            "col_padding_x": [15.0, 15.0],
            "nested_widths": [240, 240],
            "nested_same_row": True,
        }
        cases.append(dict(
            name="grid_breakpoints_gutters_and_nesting",
            passed=(actual_1 == expected_1),
            expected=expected_1,
            actual=actual_1,
        ))

        # Case 2: auto_equal_width_cols
        page.set_viewport_size({"width": 1200, "height": 900})
        auto_res = page.evaluate("""() => {
            const widths = id => Array.from(document.querySelectorAll('#' + id + ' > .col')).map(e => Math.round(e.getBoundingClientRect().width));
            const h3 = Array.from(document.querySelectorAll('#auto3 > .col')).map(e => Math.round(e.getBoundingClientRect().height));
            return {
                two_cols: widths('auto2'),
                three_cols: widths('auto3'),
                four_cols: widths('auto4'),
                three_cols_equal_height: new Set(h3).size === 1 && h3[0] > 0,
            };
        }""")
        expected_2 = {
            "two_cols": [600, 600],
            "three_cols": [400, 400, 400],
            "four_cols": [300, 300, 300, 300],
            "three_cols_equal_height": True,
        }
        cases.append(dict(
            name="auto_equal_width_cols",
            passed=(auto_res == expected_2),
            expected=expected_2,
            actual=auto_res,
        ))

        # Case 3: responsive_sm_equal_and_unequal
        page.set_viewport_size({"width": 375, "height": 900})
        mob_sm = page.evaluate("""() => {
            const eq = Array.from(document.querySelectorAll('#sm-eq > div')).map(e => ({w: Math.round(e.getBoundingClientRect().width), y: Math.round(e.getBoundingClientRect().top)}));
            const un = Array.from(document.querySelectorAll('#sm-uneq > div')).map(e => ({w: Math.round(e.getBoundingClientRect().width), y: Math.round(e.getBoundingClientRect().top)}));
            return {
                eq_widths: eq.map(x => x.w),
                eq_stacked: new Set(eq.map(x => x.y)).size === 4,
                un_widths: un.map(x => x.w),
                un_stacked: un[0].y < un[1].y,
            };
        }""")
        page.set_viewport_size({"width": 768, "height": 900})
        tab_sm = page.evaluate("""() => {
            const eq = Array.from(document.querySelectorAll('#sm-eq > div')).map(e => ({w: Math.round(e.getBoundingClientRect().width), y: Math.round(e.getBoundingClientRect().top)}));
            const un = Array.from(document.querySelectorAll('#sm-uneq > div')).map(e => ({w: Math.round(e.getBoundingClientRect().width), y: Math.round(e.getBoundingClientRect().top)}));
            return {
                eq_widths: eq.map(x => x.w),
                eq_same_row: new Set(eq.map(x => x.y)).size === 1,
                un_widths: un.map(x => x.w),
                un_same_row: un[0].y === un[1].y,
            };
        }""")
        actual_3 = {"viewport_375": mob_sm, "viewport_768": tab_sm}
        expected_3 = {
            "viewport_375": {
                "eq_widths": [375, 375, 375, 375],
                "eq_stacked": True,
                "un_widths": [375, 375],
                "un_stacked": True,
            },
            "viewport_768": {
                "eq_widths": [192, 192, 192, 192],
                "eq_same_row": True,
                "un_widths": [256, 512],
                "un_same_row": True,
            },
        }
        cases.append(dict(
            name="responsive_sm_equal_and_unequal",
            passed=(actual_3 == expected_3),
            expected=expected_3,
            actual=actual_3,
        ))

        # Case 4: multi_breakpoint_combinations
        mb_out = {}
        for vw in (375, 576, 768, 992, 1200):
            page.set_viewport_size({"width": vw, "height": 900})
            mb_out[str(vw)] = page.evaluate("""() => {
                const l = document.getElementById('mb-left').getBoundingClientRect();
                const r = document.getElementById('mb-right').getBoundingClientRect();
                return { left: Math.round(l.width), right: Math.round(r.width), same_row: Math.round(l.top) === Math.round(r.top) };
            }""")
        expected_4 = {
            "375": {"left": 375, "right": 375, "same_row": False},
            "576": {"left": 144, "right": 432, "same_row": True},
            "768": {"left": 384, "right": 384, "same_row": True},
            "992": {"left": 331, "right": 661, "same_row": True},
            "1200": {"left": 200, "right": 1000, "same_row": True},
        }
        cases.append(dict(
            name="multi_breakpoint_combinations",
            passed=(mb_out == expected_4),
            expected=expected_4,
            actual=mb_out,
        ))

        # Case 5: offset_md_columns
        page.set_viewport_size({"width": 992, "height": 900})
        off_992 = page.evaluate("""() => {
            const ml = id => Math.round(parseFloat(getComputedStyle(document.getElementById(id)).marginLeft));
            const w = id => Math.round(document.getElementById(id).getBoundingClientRect().width);
            return {
                o1a_w: w('o1a'), o1b_w: w('o1b'), o1b_ml: ml('o1b'),
                o2a_w: w('o2a'), o2a_ml: ml('o2a'), o2b_ml: ml('o2b'),
                o3a_w: w('o3a'), o3a_ml: ml('o3a'),
            };
        }""")
        page.set_viewport_size({"width": 375, "height": 900})
        off_375_ml = page.evaluate("""() => Math.round(parseFloat(getComputedStyle(document.getElementById('o1b')).marginLeft))""")
        actual_5 = {"at_992_container_960": off_992, "at_375_offset_ml": off_375_ml}
        expected_5 = {
            "at_992_container_960": {
                "o1a_w": 320, "o1b_w": 320, "o1b_ml": 320,
                "o2a_w": 240, "o2a_ml": 240, "o2b_ml": 240,
                "o3a_w": 480, "o3a_ml": 240,
            },
            "at_375_offset_ml": 0,
        }
        cases.append(dict(
            name="offset_md_columns",
            passed=(actual_5 == expected_5),
            expected=expected_5,
            actual=actual_5,
        ))

        browser.close()

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


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/bootstrap4-grid-basic-lab/explore-grid-basic.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-grid-basic.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Bootstrap4

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

下载课程关联工程包:Bootstrap4

课程关联工程包(登记关联35章) · 含当前章节或实例 · mbskycom202612a664.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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