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

Foundation 块状网格

讲解 Foundation 5 块状网格(Block Grid)使用 <ul> 与 .small|medium|large-block-grid-num 实现图片/段落等宽均分、不等高自动清浮动折行与多端列数切换,附离线实测。

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

学完这一章,你能够

块状网格用途与等宽均分写法

当需要在同一行内将一组同构元素(如商品缩略图、画廊卡片)平均分配宽度,且不想受 12 列整除限制(如 5 等分)时,Foundation 5 提供了块状网格(Block Grid)。只需在 `<ul>` 上添加 `.small|medium|large-block-grid-num` 类(`num` 表示每行均分的项数),每个列表项 `<li>` 便会去除默认项目符号、向左浮动并按 `100% / num` 均分宽度。本站离线 Chromium 实测 `<ul class="small-block-grid-3">` 内 3 张离线 SVG 占位图在 `375px`、`768px`、`1200px` 视口下全部单行均分,单项宽依次为 `125px`、`256px`、`400px`(`list-style-type: none`,内边距 `0px 10px 20px`)。

块状网格同样适用于文字段落或图文卡片,且内建了 `li:nth-of-type(Nn+1) { clear: both; }` 规则,即便同行各 `<li>` 高度不一,下一行首项也会整齐回到最左侧而不会卡在较高项右侧。本站在 `900px` 视口实测含 4 个段落(其中首项高 `60px`、其余高 `30px`)的 `.small-block-grid-3`:4 项宽度均为 `300px`,前 3 项位于首行,第 4 项自动开启新行并与首项左边缘精准对齐。

按屏幕尺寸动态调整每行块数

在同一 `<ul>` 上同时组合多个断点的块状网格类即可按屏幕宽度动态改变每行数量,例如 `class="small-block-grid-2 medium-block-grid-3 large-block-grid-4"` 表示手机每行 2 块、平板每行 3 块、桌面每行 4 块。本站离线实测该 4 项网格跨三档视口的排版结果:`375px` 下每项宽 `187.5px`、呈 `[2, 2]` 两行排列;`768px` 下每项宽 `256px`、呈 `[3, 1]` 排列;`1200px` 下每项宽 `300px`、呈 `[4]` 单行铺开。

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

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 在离线 Chromium 中核对 .small-block-grid-3 在 375px/768px/1200px 的三等分宽度与间距、不等高 4 项段落网格的 3n+1 清浮动折行,以及 small-2/medium-3/large-4 在三档视口的每行项数([2,2]、[3,1]、[4])。
离线实测 Foundation 5 块状网格图片/段落三等分、不等高折行与 2/3/4 响应式切列

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

当前源码 SHA256:cbac8d1c095b7b41bcceda98de6262fe98e7ab4145a48924250ffcb666a2e32c

下载本站示例源码

本地运行

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

下载Foundation 块状网格实验

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

ZIP SHA256:922815c04a6ca9793f0436fcfaf150e84a92cb6fd24a5a1c7021926652c5e512

常见错误与边界

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

练习与解答

在 Foundation 5 中,块状网格(block-grid)相比普通 12 列网格 .row/.columns 有哪些优势?当同行卡片高度不一致时为何不会错位?

展开参考解答

块状网格只需在 <ul> 上声明每行项数即可自动均分宽度,支持 5 等分等非 12 约数布局且无需手动切分多行 .row;同时 Foundation 为每档 block-grid 生成了 :nth-of-type(Nn+1) { clear: both; } 规则,强制每行首项清除浮动,避免不等高卡片产生阶梯错位。

规范与官方依据