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

离线实测 Foundation 5 块状网格图片/段落三等分、不等高折行与 2/3/4 响应式切列

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

FOUNDATION_BLOCK_GRID_CSS = """
*, *::before, *::after { box-sizing: border-box; }
html { font-size: 16px; }
body { margin: 0; padding: 0 0.625rem; font-family: "Helvetica Neue", Helvetica, Roboto, Arial, sans-serif; }
[class*="block-grid-"] { display: block; padding: 0; margin: 0 -0.625rem; list-style: none; }
[class*="block-grid-"]::before, [class*="block-grid-"]::after { content: " "; display: table; }
[class*="block-grid-"]::after { clear: both; }
[class*="block-grid-"] > li { display: block; height: auto; float: left; padding: 0 0.625rem 1.25rem; list-style: none; }
.small-block-grid-2 > li { width: 50%; }
.small-block-grid-2 > li:nth-of-type(1n) { clear: none; }
.small-block-grid-2 > li:nth-of-type(2n+1) { clear: both; }
.small-block-grid-3 > li { width: 33.33333%; }
.small-block-grid-3 > li:nth-of-type(1n) { clear: none; }
.small-block-grid-3 > li:nth-of-type(3n+1) { clear: both; }
@media only screen and (min-width: 40.0625em) {
  .medium-block-grid-3 > li { width: 33.33333%; }
  .medium-block-grid-3 > li:nth-of-type(1n) { clear: none; }
  .medium-block-grid-3 > li:nth-of-type(3n+1) { clear: both; }
}
@media only screen and (min-width: 64.0625em) {
  .large-block-grid-4 > li { width: 25%; }
  .large-block-grid-4 > li:nth-of-type(1n) { clear: none; }
  .large-block-grid-4 > li:nth-of-type(4n+1) { clear: both; }
}
img { display: block; width: 100%; height: 60px; }
"""

SVG_IMG = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='200' height='60'><rect width='200' height='60' fill='%234a90d9'/></svg>"

HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{FOUNDATION_BLOCK_GRID_CSS}</style></head>
<body>
  <ul id="bg-img" class="small-block-grid-3">
    <li><img src="{SVG_IMG}" alt="City 1"></li>
    <li><img src="{SVG_IMG}" alt="City 2"></li>
    <li><img src="{SVG_IMG}" alt="City 3"></li>
  </ul>
  <ul id="bg-text" class="small-block-grid-3">
    <li><p style="height:60px;margin:0;">第一块较长段落示例文本</p></li>
    <li><p style="height:30px;margin:0;">第二块示例文本</p></li>
    <li><p style="height:30px;margin:0;">第三块示例文本</p></li>
    <li><p style="height:30px;margin:0;">第四块自动换行</p></li>
  </ul>
  <ul id="bg-resp" class="small-block-grid-2 medium-block-grid-3 large-block-grid-4">
    <li><img src="{SVG_IMG}" alt="Item 1"></li>
    <li><img src="{SVG_IMG}" alt="Item 2"></li>
    <li><img src="{SVG_IMG}" alt="Item 3"></li>
    <li><img src="{SVG_IMG}" alt="Item 4"></li>
  </ul>
</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": 375, "height": 900})
        page.set_content(HTML_PAGE)

        # Case 1: .small-block-grid-3 with images evenly splits across 375, 768, 1200px
        actual_1 = {}
        for vw in (375, 768, 1200):
            page.set_viewport_size({"width": vw, "height": 900})
            actual_1[str(vw)] = page.evaluate("""() => {
                const lis = Array.from(document.querySelectorAll('#bg-img > li'));
                const rects = lis.map(el => el.getBoundingClientRect());
                const cs = getComputedStyle(lis[0]);
                return {
                    widths: rects.map(r => Math.round(r.width * 10) / 10),
                    same_row: rects.every(r => Math.abs(r.top - rects[0].top) < 1),
                    list_style: cs.listStyleType,
                    padding: cs.padding,
                };
            }""")
        expected_1 = {
            "375": {"widths": [125.0, 125.0, 125.0], "same_row": True, "list_style": "none", "padding": "0px 10px 20px"},
            "768": {"widths": [256.0, 256.0, 256.0], "same_row": True, "list_style": "none", "padding": "0px 10px 20px"},
            "1200": {"widths": [400.0, 400.0, 400.0], "same_row": True, "list_style": "none", "padding": "0px 10px 20px"},
        }
        cases.append({
            "name": "small_block_grid_3_images_even_split",
            "expected": expected_1,
            "actual": actual_1,
            "passed": actual_1 == expected_1,
        })

        # Case 2: .small-block-grid-3 paragraphs + nth-of-type(3n+1) clean row wrap on unequal heights
        page.set_viewport_size({"width": 900, "height": 900})
        actual_2 = page.evaluate("""() => {
            const lis = Array.from(document.querySelectorAll('#bg-text > li'));
            const rects = lis.map(el => el.getBoundingClientRect());
            return {
                widths: rects.map(r => Math.round(r.width * 10) / 10),
                first_three_same_row: Math.abs(rects[0].top - rects[1].top) < 1 && Math.abs(rects[1].top - rects[2].top) < 1,
                fourth_starts_new_row: rects[3].top >= rects[0].bottom - 1,
                fourth_aligned_left: Math.abs(rects[3].left - rects[0].left) < 1,
            };
        }""")
        expected_2 = {
            "widths": [300.0, 300.0, 300.0, 300.0],
            "first_three_same_row": True,
            "fourth_starts_new_row": True,
            "fourth_aligned_left": True,
        }
        cases.append({
            "name": "small_block_grid_3_paragraphs_and_wrapping",
            "expected": expected_2,
            "actual": actual_2,
            "passed": actual_2 == expected_2,
        })

        # Case 3: Responsive .small-block-grid-2 .medium-block-grid-3 .large-block-grid-4
        actual_3 = {}
        for vw in (375, 768, 1200):
            page.set_viewport_size({"width": vw, "height": 900})
            actual_3[str(vw)] = page.evaluate("""() => {
                const lis = Array.from(document.querySelectorAll('#bg-resp > li'));
                const rects = lis.map(el => el.getBoundingClientRect());
                const rows = [];
                for (const r of rects) {
                    const last = rows[rows.length - 1];
                    if (last && Math.abs(last.top - r.top) < 1) {
                        last.count += 1;
                    } else {
                        rows.push({ top: r.top, count: 1 });
                    }
                }
                return {
                    item_width: Math.round(rects[0].width * 10) / 10,
                    items_per_row: rows.map(x => x.count),
                };
            }""")
        expected_3 = {
            "375": {"item_width": 187.5, "items_per_row": [2, 2]},
            "768": {"item_width": 256.0, "items_per_row": [3, 1]},
            "1200": {"item_width": 300.0, "items_per_row": [4]},
        }
        cases.append({
            "name": "responsive_block_grid_2_3_4_across_viewports",
            "expected": expected_3,
            "actual": actual_3,
            "passed": actual_3 == expected_3,
        })

        browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


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

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

入口文件:projects/foundation-grid-block-lab/explore-grid-block.py

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

下载课程关联工程包:Foundation

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

下载课程关联工程包:Foundation

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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