网格包装器

网格包装器模式在将网格内容对齐到中心包装器内的同时,还允许项目突破并对齐到其包含元素或页面的边缘,这非常有用。

依赖项

放置在网格上的项目应该能够对齐到水平居中的最大宽度包装器或网格的外边缘,或两者兼而有之。

示例

点击下面代码块中的“Play”按钮,在 MDN Playground 中编辑示例。

html
<div class="grid">
  <div class="wrapper">
    <p>
      This item aligns to a central “wrapper” – columns that have a maximum
      width.
    </p>
  </div>
  <div class="full-width">
    <p>This item aligns to the edge of the grid container.</p>
  </div>
  <div class="left-edge">
    <p>
      This item aligns to the left edge of the grid container and the right edge
      of the wrapper.
    </p>
  </div>
  <div class="right-wrapper">
    <p>This item aligns to the right edge of the “wrapper” columns.</p>
  </div>
</div>
css
body {
  font: 1.2em sans-serif;
}
.grid {
  display: grid;
  grid-template-columns: minmax(20px, 1fr) repeat(6, minmax(0, 60px)) minmax(
      20px,
      1fr
    );
  grid-auto-rows: minmax(100px, auto);
  grid-gap: 10px;
}

.grid > * {
  border: 2px solid rgb(95 97 110);
  border-radius: 0.5em;
  padding: 20px;
}

.full-width {
  grid-column: 1 / -1;
}

.wrapper {
  grid-column: 2 / -2;
}

.left-edge {
  grid-column: 1 / -2;
}

.right-wrapper {
  grid-column: 4 / -2;
}

已做出的选择

此食谱使用 CSS 网格 minmax() 函数在 grid-template-columns 属性中定义网格轨道大小。对于具有最大宽度的中心列,我们可以设置一个大于或等于 0 的最小值和一个指定列轨道将增长到的最大大小的最大值。使用相对绝对 <length> 单位(像素、em、rem)将为中心包装器创建固定的最大大小,而使用<percentage> 值或视口单位将导致包装器根据其上下文进行放大或缩小。

外侧两列的最大大小为 1fr,这意味着它们将各自扩展以填充网格容器中剩余的可用空间。

有用的备用方案或替代方法

要水平居中网格页面,您可以设置 max-width 以及左右 auto margin

css
.grid {
  max-width: 96vw; /* Limits the width to 96% of the width of the viewport */
  margin: 0 auto; /* horizontally centers the container */
}

可访问性考虑

尽管 CSS 网格允许在任何位置(在合理范围内)定位项目,但确保您的底层标记遵循逻辑顺序非常重要(有关更多详细信息,请参阅CSS 网格布局和可访问性)。

另见