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

Ionic 网格(Grid)

系统梳理 Ionic 1 基于 CSS Flexbox 的网格系统:等宽行/列(row/col)、九档百分比列宽(col-10..col-90)、九档左侧偏移(col-offset-10..col-offset-90)、行/列级纵向对齐以及三档响应式断点。

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

学完这一章,你能够

弹性盒子模型与等宽网格

与早期依赖浮动(float)的桌面网格框架不同,Ionic 1 的网格系统原生采用 CSS 弹性盒子模型(Flexible Box Model),适配绝大多数现代移动浏览器。核心约定十分简洁:`.row` 声明水平弹性行容器,内部每个 `.col` 默认等分整行剩余宽度——例如一行内放入 5 个 `.col` 时,每列自动获得 20% 宽度,无需手动计算分栏总数。

指定百分比列宽与自动补齐机制

需要不等宽排版时,可为指定列叠加百分比宽度类(Ionic 1 内置 `.col-10` 至 `.col-90` 共九档百分比规则;需客观说明:虽然传统网格概念常按 12 栏类比,Ionic 1 实际按 `flex: 0 0 <pct>%` 百分比设定显式列宽,同行内其余未声明宽度的普通 `.col` 会自动平分剩余空间,例如 `col-50` 搭配两个 `.col` 时三列分别为 50%、25%、25%,`col-75` 搭配一个 `.col` 时为 75%、25%)。演示页面通常还会为 `.col` 额外添加浅灰背景与边框以便观察网格边界。

列偏移量(col-offset-*)与纵向对齐

通过 `.col-offset-10` 至 `.col-offset-90` 九档偏移类可为列设置对应的 `margin-left` 百分比左偏移,例如 `.col-33.col-offset-33` 会先空出左侧约 33.3333% 空间再占据约 33.3333% 宽度,紧随其后的无宽度 `.col` 自动填满余下 33.3333%。

借助 Flexbox 的交叉轴对齐能力,网格同时支持单列级与整行级纵向对齐:给单个列添加 `.col-top`、`col-center` 或 `col-bottom` 分别映射 `align-self: flex-start / center / flex-end`;给整行添加 `.row-top`、`row-center` 或 `row-bottom` 则通过 `align-items` 统一对齐行内全部列(示例中最后一列通过多行换行撑高整行以凸显垂直对齐差异)。

响应式网格断点与现代 ion-grid 对照

移动设备在竖屏、横屏与平板之间切换时,可给 `.row` 添加三档响应式类让横向多列在窄屏下自动换行堆叠为单列:`.responsive-sm` 在视口宽度小于等于 567px(小于手机横屏)时堆叠,`.responsive-md` 在小于等于 767px(小于平板竖屏)时堆叠,`.responsive-lg` 在小于等于 1023px(小于平板横屏)时堆叠。源页面的 5 个示例按钮仅作静态登记;现代 Ionic 7/8 则演进为标准 12 栏 Flexbox `<ion-grid><ion-row><ion-col size="6" size-md="4" offset="2">` 组件。

Ionic 1 指定列宽百分比样式表

样式类列宽百分比Flexbox 行为说明
.col-1010%设置列弹性基准宽度为 10%(flex: 0 0 10%;max-width: 10%)。
.col-2020%设置列弹性基准宽度为 20%(五等分单列宽度)。
.col-2525%设置列弹性基准宽度为 25%(四等分单列宽度)。
.col-3333.3333%设置列弹性基准宽度为 33.3333%(三等分单列宽度)。
.col-5050%设置列弹性基准宽度为 50%(二等分半宽)。
.col-6766.6666%设置列弹性基准宽度为 66.6666%(三分之二宽)。
.col-7575%设置列弹性基准宽度为 75%(四分之三宽)。
.col-8080%设置列弹性基准宽度为 80%(五分之四宽)。
.col-9090%设置列弹性基准宽度为 90%(十分之九宽)。

Ionic 1 列左侧偏移量样式表

偏移类左偏移百分比CSS 属性说明
.col-offset-1010%为当前列施加 margin-left: 10%。
.col-offset-2020%为当前列施加 margin-left: 20%。
.col-offset-2525%为当前列施加 margin-left: 25%。
.col-offset-3333.3333%为当前列施加 margin-left: 33.3333%。
.col-offset-5050%为当前列施加 margin-left: 50%。
.col-offset-6766.6666%为当前列施加 margin-left: 66.6666%。
.col-offset-7575%为当前列施加 margin-left: 75%。
.col-offset-8080%为当前列施加 margin-left: 80%。
.col-offset-9090%为当前列施加 margin-left: 90%。

Ionic 1 响应式网格断点类

响应式类触发阈值与布局变化
.responsive-sm小于手机横屏(视口 <= 567px)时将水平 .row 转为纵向单列堆叠。
.responsive-md小于平板竖屏(视口 <= 767px)时将水平 .row 转为纵向单列堆叠。
.responsive-lg小于平板横屏(视口 <= 1023px)时将水平 .row 转为纵向单列堆叠。

运行 Ionic 1 Flexbox 等宽列、百分比列宽、偏移量、纵向对齐与三档响应式断点离线核验

python · 阅读源码
"""Offline Ionic 1 Flexbox Grid (equal cols, col-*, col-offset-*, vertical align & responsive breakpoints) verifier for Ch15 (grid)."""
from __future__ import annotations

import json
from lxml import html

VERSION = "CPython 3.12.14 / lxml offline Ionic UI & component verifier"

COL_PCT = {
    "col-10": 10.0,
    "col-20": 20.0,
    "col-25": 25.0,
    "col-33": 33.3333,
    "col-50": 50.0,
    "col-67": 66.6666,
    "col-75": 75.0,
    "col-80": 80.0,
    "col-90": 90.0,
}

OFFSET_PCT = {f"col-offset-{k.split('-')[1]}": v for k, v in COL_PCT.items()}

RESPONSIVE_BREAKPOINTS = {
    "responsive-sm": 567,
    "responsive-md": 767,
    "responsive-lg": 1023,
}


def make_case(name: str, summary: str, expected, actual) -> dict:
    return {
        "name": name,
        "summary": summary,
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def compute_row_widths(row_el) -> list[dict]:
    cols = row_el.xpath("./div[contains(concat(' ', @class, ' '), ' col ')]")
    explicit_sum = 0.0
    flex_count = 0
    specs = []
    for c in cols:
        cls = c.get("class", "").split()
        w = next((COL_PCT[k] for k in cls if k in COL_PCT), None)
        off = next((OFFSET_PCT[k] for k in cls if k in OFFSET_PCT), 0.0)
        if w is not None:
            explicit_sum += w + off
        else:
            explicit_sum += off
            flex_count += 1
        specs.append((w, off))
    rem = max(0.0, 100.0 - explicit_sum)
    each_flex = round(rem / flex_count, 4) if flex_count else 0.0
    return [
        {"width_pct": round(w, 4) if w is not None else each_flex, "offset_pct": round(off, 4)}
        for w, off in specs
    ]


def case_equal_and_explicit_columns() -> dict:
    markup = """
    <section>
      <div class="row">
        <div class="col">.col</div>
        <div class="col">.col</div>
        <div class="col">.col</div>
        <div class="col">.col</div>
        <div class="col">.col</div>
      </div>
      <div class="row">
        <div class="col col-50">.col.col-50</div>
        <div class="col">.col</div>
        <div class="col">.col</div>
      </div>
      <div class="row">
        <div class="col col-75">.col.col-75</div>
        <div class="col">.col</div>
      </div>
      <div class="row">
        <div class="col">.col</div>
        <div class="col col-75">.col.col-75</div>
      </div>
      <div class="row">
        <div class="col">.col</div>
        <div class="col">.col</div>
      </div>
    </section>
    """
    root = html.fragment_fromstring(markup)
    rows = [compute_row_widths(r) for r in root.xpath("./div[@class='row']")]
    actual = {
        "row1_5_equal_widths": [c["width_pct"] for c in rows[0]],
        "row2_50_plus_2_auto": [c["width_pct"] for c in rows[1]],
        "row3_75_plus_auto": [c["width_pct"] for c in rows[2]],
        "row4_auto_plus_75": [c["width_pct"] for c in rows[3]],
        "row5_2_equal": [c["width_pct"] for c in rows[4]],
        "explicit_class_count": len(COL_PCT),
    }
    expected = {
        "row1_5_equal_widths": [20.0, 20.0, 20.0, 20.0, 20.0],
        "row2_50_plus_2_auto": [50.0, 25.0, 25.0],
        "row3_75_plus_auto": [75.0, 25.0],
        "row4_auto_plus_75": [25.0, 75.0],
        "row5_2_equal": [50.0, 50.0],
        "explicit_class_count": 9,
    }
    return make_case(
        "grid_equal_and_percentage_columns",
        "Verify flexbox equal-width .col distribution and all 9 .col-* explicit percentage widths",
        expected,
        actual,
    )


def case_offset_columns() -> dict:
    markup = """
    <section>
      <div class="row">
        <div class="col col-33 col-offset-33">.col</div>
        <div class="col">.col</div>
      </div>
      <div class="row">
        <div class="col col-33">.col</div>
        <div class="col col-33 col-offset-33">.col</div>
      </div>
      <div class="row">
        <div class="col col-33 col-offset-67">.col</div>
      </div>
    </section>
    """
    root = html.fragment_fromstring(markup)
    rows = [compute_row_widths(r) for r in root.xpath("./div[@class='row']")]
    actual = {
        "offset_class_count": len(OFFSET_PCT),
        "row1": rows[0],
        "row2": rows[1],
        "row3": rows[2],
    }
    expected = {
        "offset_class_count": 9,
        "row1": [
            {"width_pct": 33.3333, "offset_pct": 33.3333},
            {"width_pct": 33.3334, "offset_pct": 0.0},
        ],
        "row2": [
            {"width_pct": 33.3333, "offset_pct": 0.0},
            {"width_pct": 33.3333, "offset_pct": 33.3333},
        ],
        "row3": [
            {"width_pct": 33.3333, "offset_pct": 66.6666},
        ],
    }
    return make_case(
        "grid_column_offsets",
        "Verify .col-offset-* left-margin calculation and remaining flex column sizing",
        expected,
        actual,
    )


def case_vertical_alignment() -> dict:
    markup = """
    <section>
      <div class="row">
        <div class="col col-top">.col</div>
        <div class="col col-center">.col</div>
        <div class="col col-bottom">.col</div>
        <div class="col">1<br>2<br>3<br>4</div>
      </div>
      <div class="row row-top"><div class="col">.col</div></div>
      <div class="row row-center"><div class="col">.col</div></div>
      <div class="row row-bottom"><div class="col">.col</div></div>
    </section>
    """
    root = html.fragment_fromstring(markup)
    flex_map = {
        "col-top": "flex-start",
        "col-center": "center",
        "col-bottom": "flex-end",
        "row-top": "flex-start",
        "row-center": "center",
        "row-bottom": "flex-end",
    }
    col_aligns = [
        flex_map[next(k for k in c.get("class", "").split() if k in flex_map)]
        for c in root.xpath("./div[1]/div")[:3]
    ]
    row_aligns = [
        flex_map[next(k for k in r.get("class", "").split() if k in flex_map)]
        for r in root.xpath("./div")[1:]
    ]
    actual = {
        "per_column_align_self": col_aligns,
        "per_row_align_items": row_aligns,
    }
    expected = {
        "per_column_align_self": ["flex-start", "center", "flex-end"],
        "per_row_align_items": ["flex-start", "center", "flex-end"],
    }
    return make_case(
        "grid_vertical_alignment",
        "Verify col-top/center/bottom (align-self) and row-top/center/bottom (align-items) flexbox rules",
        expected,
        actual,
    )


def case_responsive_breakpoints() -> dict:
    markup = """
    <div class="row responsive-sm">
      <div class="col">.col</div>
      <div class="col">.col</div>
      <div class="col">.col</div>
      <div class="col">.col</div>
    </div>
    """
    root = html.fragment_fromstring(markup)
    resp_cls = [c for c in root.get("class", "").split() if c.startswith("responsive-")][0]

    def layout_direction(cls_name: str, viewport_w: int) -> str:
        return "column" if viewport_w <= RESPONSIVE_BREAKPOINTS[cls_name] else "row"

    actual = {
        "responsive_class": resp_cls,
        "col_count": len(root.xpath("./div[@class='col']")),
        "sm_at_375px": layout_direction("responsive-sm", 375),
        "sm_at_640px": layout_direction("responsive-sm", 640),
        "md_at_767px": layout_direction("responsive-md", 767),
        "md_at_800px": layout_direction("responsive-md", 800),
        "lg_at_1023px": layout_direction("responsive-lg", 1023),
        "lg_at_1280px": layout_direction("responsive-lg", 1280),
    }
    expected = {
        "responsive_class": "responsive-sm",
        "col_count": 4,
        "sm_at_375px": "column",
        "sm_at_640px": "row",
        "md_at_767px": "column",
        "md_at_800px": "row",
        "lg_at_1023px": "column",
        "lg_at_1280px": "row",
    }
    return make_case(
        "grid_responsive_stacking_breakpoints",
        "Verify .responsive-sm (<=567px), .responsive-md (<=767px), and .responsive-lg (<=1023px) stacking thresholds",
        expected,
        actual,
    )


def main() -> None:
    cases = [
        case_equal_and_explicit_columns(),
        case_offset_columns(),
        case_vertical_alignment(),
        case_responsive_breakpoints(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 验证 5 列等宽(20%)、`col-50`/`col-75` 剩余空间自动平分、9 档 `col-*` 与 `col-offset-*` 计算、`col-*`/`row-*` 纵向对齐及 567px/767px/1023px 堆叠切换。
运行 Ionic 1 Flexbox 等宽列、百分比列宽、偏移量、纵向对齐与三档响应式断点离线核验

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

当前源码 SHA256:22fa4ebbdce4f6382cb9c32ce7c172ae181a42030a7686a68cc8d2168d181495

下载本站示例源码

本地运行

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

下载Ionic 网格(Grid)实验

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

ZIP SHA256:f93eb5f40faa40046273771c3069156b8585ca17179b4795dd4cdc01a26ebcf1

常见错误与边界

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

练习与解答

在一行 `<div class="row">` 中放入一个 `.col.col-50` 和两个普通 `.col`,三列最终各占多大宽度?`.row-center` 与 `.col-center` 的作用范围有何区别?

展开参考解答

第一列固定占 50%,其余两个普通 `.col` 平分剩余的 50% 即各占 25%;`.row-center` 通过 `align-items: center` 让整行所有列垂直居中,`.col-center` 通过 `align-self: center` 仅控制当前单个列垂直居中。

规范与官方依据