Bootstrap 大屏幕网格
Bootstrap 网格系统 - 大型设备及以上
Section titled “Bootstrap 网格系统 - 大型设备及以上”Bootstrap 网格示例:适应大型设备
Section titled “Bootstrap 网格示例:适应大型设备”Bootstrap 的 grid system(网格系统)设计理念是移动设备优先,然后向上扩展到更大的屏幕尺寸。你可以为不同的 breakpoint(断点)(例如 small、medium、large、extra-large)定义不同的 column(列)布局。
假设你的布局在小型设备(.col-sm-*)上是 25%/75%,在中型设备(.col-md-*)上是 50%/50%:
<div class="row"> <div class="col-sm-3 col-md-6">....</div> <div class="col-sm-9 col-md-6">....</div></div>对于大型设备,你可能更喜欢 33%/66% 的布局。Bootstrap 的 large breakpoint(lg)默认从 992 像素及以上的屏幕宽度开始。Bootstrap 5 还包含 extra-large(xl >= 1200px)和 extra-extra-large(xxl >= 1400px)的 breakpoint。
要为大型设备添加特定布局,可以使用 .col-lg-* class。让我们调整示例,使其在大型屏幕上使用 4/12 (33%) 和 8/12 (66%) 的分割:
<div class="row"> <div class="col-sm-3 col-md-6 col-lg-4">....</div> <div class="col-sm-9 col-md-6 col-lg-8">....</div></div>Bootstrap 会应用当前屏幕尺寸下最大的有效 breakpoint。因此,在大型屏幕上,它会使用 .col-lg-*。在中型屏幕上,它会回退到 .col-md-*,在小型屏幕上则回退到 .col-sm-*。如果没有指定 sm、md、lg 等 class,除非使用了基础的 col-* class,否则在超小型屏幕上列会默认垂直堆叠。
这是一个演示此行为的完整示例:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Responsive Grid Example</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet"> <style> /* Added for visual clarity */ .demo-col { padding: 15px; margin-bottom: 15px; } </style></head><body> <div class="container-fluid mt-3"> <h1>Responsive Columns</h1> <p>Resize your browser window to see the column widths change based on screen size.</p> <div class="row"> <div class="col-sm-3 col-md-6 col-lg-4 demo-col" style="background-color:#e9ecef;"> <p>This column is <code>col-sm-3</code>, <code>col-md-6</code>, <code>col-lg-4</code>.</p> <p>Content for the first column. Try resizing!</p> </div> <div class="col-sm-9 col-md-6 col-lg-8 demo-col" style="background-color:#f8f9fa;"> <p>This column is <code>col-sm-9</code>, <code>col-md-6</code>, <code>col-lg-8</code>.</p> <p>Content for the second column. This will adapt differently based on the screen width, demonstrating the power of Bootstrap's responsive grid.</p> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script></body></html>| | 重要的网格概念:
- 行 (
.row): 作为列的包裹容器。如果使用了 gutter,它们会使用负外边距抵消列的内边距。 - 列 (
.col-*-*): 定义内容区域的宽度。理想情况下,一行中列数的总和应为 12。 - Gutters(槽宽/间隙): 列之间的间距。Bootstrap 5 在
.row上使用gx-*(水平)、gy-*(垂直)和g-*(水平和垂直)等 utility class(工具类)来控制 gutter 宽度。例如,g-3添加了标准 gutter。 - Breakpoints(断点): Bootstrap 预定义了 breakpoint(xs、sm、md、lg、xl、xxl)。你可以为每个断点指定列的行为。 | | --- | --- |
记住,始终将 column 放置在 .row 内或使用 display: flex 的元素内。这能确保正确的对齐和间距。