Bootstrap4 网格系统
核对 Bootstrap 4 基于 Flexbox 的 12 列移动优先网格体系、五档断点类前缀、行/列负边距间隙规则、自动等宽列、多断点响应式组合及 .offset-*-* 列偏移实测。
学完这一章,你能够
- 核对 Bootstrap 4 基于 Flexbox 的 12 列移动优先网格体系、五档断点类前缀、行/列负边距间隙规则、自动等宽列、多断点响应式组合及 .offset-*-* 列偏移实测。
12 列响应式网格与五档断点类
Bootstrap 4 提供响应式、移动设备优先的 12 列流式网格系统,单行最多划分为 12 等份,并可按需组合成等宽或不等宽列(如 12×1、3×4、4+8、6+6 或整行 12 列),列排布会随视口尺寸变化自动重排。
网格类按屏幕宽度划分 5 档前缀:`.col-`(所有设备,含 `<576px` 超小屏)、`.col-sm-`(`≥576px` 平板/大屏手机)、`.col-md-`(`≥768px` 桌面端)、`.col-lg-`(`≥992px` 大桌面)与 `.col-xl-`(`≥1200px` 超大桌面)。
网格布局规则与 Flexbox 机制
使用网格需遵循核心结构约束:每一行 `.row` 应置于 `.container` 或 `.container-fluid` 容器内;`.row` 负责组建水平列组,且只有列元素应作为 `.row` 的直接子元素;列之间通过左右各 `15px` 内边距形成 `30px` 间隙,而 `.row` 的左右 `-15px` 负外边距负责抵消首尾两列的外侧留白以与容器对齐。与 Bootstrap 3 依赖浮动不同,Bootstrap 4 全面采用 Flexbox,未指定数字的 `.col` 会自动平分剩余宽度且同行各列自动等高;此外网格支持在列内部嵌套新的 `.row` 及列排序,且各断点类可组合叠加。本站实测 `992px` 视口下 `.row` 的外边距为 `[-15px, -15px]`、列内边距为 `[15px, 15px]`,半宽列内嵌套两个 `.col-6` 各占 `240px` 并同行显示。
网格基本结构与自动等宽列
网格基本写法分为显式列数(`.col-*-*`,第一星号为断点、第二星号为总和不超过 12 的列数)与自动布局(仅写 `.col` 或 `.col-sm|md|lg|xl`)。本站于 `1200px` 全宽容器实测:2 个 `.col` 各宽 `600px`(50%)、3 个 `.col` 各宽 `400px`(33.33% 且内容不等时自动等高)、4 个 `.col` 各宽 `300px`(25%)。
响应式等宽、不等宽与多断点组合
使用 `.col-sm-*` 可在 `<576px` 手机端自动上下堆叠、在 `≥576px` 设备上横向并排。本站实测:4 个 `.col-sm-3` 与 `.col-sm-4` + `.col-sm-8` 在 `375px` 下全部堆叠为 `375px` 满宽;在 `768px` 全宽容器下,前者四等分为 `[192, 192, 192, 192]px`,后者按 4:8 比例分为 `256px` 与 `512px`。
在同一列上叠加多档断点类即可按屏幕动态改变比例。例如将 `.col-sm-3.col-md-6.col-lg-4.col-xl-2` 与 `.col-sm-9.col-md-6.col-lg-8.col-xl-10` 配对置于 `.container-fluid` 中,本站跨 5 档视口实测左右列宽依次为:`375px` 堆叠(`375 / 375`)、`576px` 25%/75%(`144 / 432`)、`768px` 50%/50%(`384 / 384`)、`992px` 33.33%/66.67%(`331 / 661`)、`1200px` 16.67%/83.33%(`200 / 1000`)。
偏移列 .offset-*-*
列偏移通过 `.offset-*-*`(断点取 `sm/md/lg/xl`,列数取 `1` 到 `11`)为目标列增加对应列宽的左侧 `margin-left`。例如 `.offset-md-4` 在 `≥768px` 视口下将列向右推移 4 列。本站在 `992px` 视口(`.container` 宽 `960px`,每列 `80px`)实测:`.col-md-4.offset-md-4` 宽 `320px` 且左外边距 `320px`;两列 `.col-md-3.offset-md-3` 各宽 `240px` 且左外边距 `240px`;居中列 `.col-md-6.offset-md-3` 宽 `480px`、左外边距 `240px`;切回 `375px` 视口时左外边距自动归零为 `0px`。
12 列网格典型划分方案
| 划分组合 | 列数总和 | 典型布局场景 |
|---|---|---|
| 12 × 1 列 | 12 | 最细粒度 12 等分基础刻度 |
| 4 + 4 + 4(三等分) | 12 | 三栏特性卡片或内容概览(33.33% 等宽) |
| 4 + 8(非对称两栏) | 12 | 左侧边栏 33.33% 与右侧主内容 66.67% |
| 6 + 6(双等分) | 12 | 左右均分 50%/50% 对照面板 |
| 12(单栏通宽) | 12 | 移动端堆叠或通栏横幅区块 |
Bootstrap 4 网格五档断点参数对照表
| 属性项 | 超小 (<576px) | 平板 (≥576px) | 桌面 (≥768px) | 大桌面 (≥992px) | 超大桌面 (≥1200px) |
|---|---|---|---|---|---|
| 容器最大宽度 | None (auto) | 540px | 720px | 960px | 1140px |
| 类前缀 | .col- | .col-sm- | .col-md- | .col-lg- | .col-xl- |
| 列数量和 | 12 | 12 | 12 | 12 | 12 |
| 间隙宽度 | 30px(每列左右各 15px) | 30px(每列左右各 15px) | 30px(每列左右各 15px) | 30px(每列左右各 15px) | 30px(每列左右各 15px) |
| 可嵌套 | Yes | Yes | Yes | Yes | Yes |
| 列排序 | Yes | Yes | Yes | Yes | Yes |
离线验证 Bootstrap 4 12 列 Flexbox 网格、多断点切换与列偏移
"""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()
- 在离线 Chromium 中核对五档容器宽度、30px 列间隙与嵌套行、.col 自动平分等高、.col-sm-* 堆叠与并排、四断点组合比例及 .offset-md-* 左外边距。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:5a165f9af81ca0c7a7c815ec3261cb32cdc7bbf65a5979cbaa090b9d5be1b9a1
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:456a2fea5a54715ab740a0392ea795e7bfa4bfbea596c3c0e50e43ede91c5e0c
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么 Bootstrap 4 要求 .row 必须放在 .container 或 .container-fluid 内?.offset-md-3 在手机端会产生偏移吗?
展开参考解答
.row 带有左右 -15px 负外边距以抵消列元素左右 15px 的内边距间隙,外层容器的左右 15px 内边距正好承接该负边距以防止水平溢出;.offset-md-3 仅在视口 ≥768px 的媒体查询内生效,在 375px 等手机端左外边距自动归零为 0px。