如何在 Material Components Web (MDC) 中集中单元格?

How to centralize cells in Material Components Web (MDC)?

我想要一个集中的网格单元格,例如在桌面上有 6 列。在 docs 中,它表示:

The grid is by default center aligned. You can add mdc-layout-grid--align-left or mdc-layout-grid--align-right modifier class to change this behavior.

然后我输入:

<div class="mdc-layout-grid">
  <div class="mdc-layout-grid__inner">
    <div class="mdc-layout-grid__cell mdc-layout-grid__cell--span-3-desktop">first</div>
    <div class="mdc-layout-grid__cell mdc-layout-grid__cell--span-3-desktop">second</div>
  </div>
</div>

期待在桌面上:

| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
|---|---|---|---|---|---|---|---|---|----|----|----|
| ~ | ~ | ~ |   first   |  second   | ~  |  ~ | ~  |

而不是真正的输出:

| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
|---|---|---|---|---|---|---|---|---|----|----|----|
|   first   |  second   | ~ | ~ | ~ | ~  |  ~ |  ~ |

如何让细胞保持集中?

网格居中对齐,网格单元格间距未与网格中心对齐(您似乎假设如此)。因此,如果您将网格的宽度设置为相对于其容器的 50%,并使您的单元格的跨度宽度为 6,这将在桌面上产生所需的效果。或者,您可以在第一个单元格之前添加一个跨度宽度为 3 的空单元格。但是对于其他屏幕尺寸(在平板电脑和 phone 上,网格默认使用 8 和 4 个单元格宽度)调整起来有点困难。

由于列跨度在平板电脑上为 8,在 phone 上为 4,并且您没有指定您希望单元格在此类设备上的播放方式

使用 CSS 网格,您可以使用 grid-column-start property.

指定网格单元格的起始位置

因此,在您的示例中,您希望第一个单元格位于第 4 列:

// MDC Web's default desktop breakpoint is 840px.
@media (min-width: 840px) {
  .mdc-layout-grid__cell:first-child {
    grid-column-start: 4;
  }
}

如果 mdc-layout-grid__inner 中的单元格超过 2 个,则需要为每个奇数单元格指定起始位置:

// Specify start position for odd cells.
// :nth-child(2n+1) is more flexible than :nth-child(odd)
// as you can use this pattern for 3, 4, etc. cells in a row (3n+1, 4n+1, etc.).
@media (min-width: 840px) {
  .mdc-layout-grid__cell:nth-child(2n+1) {
    grid-column-start: 4;
  }
}

此外,您可以为 flexbox 回退指定网格对齐方式:

@media (min-width: 840px) {
  .mdc-layout-grid__inner {
    justify-content: center;
  }
}

您可以查看the demo on Codepen.

这可以通过将每种类型的设备的网格单元格跨度指定为每个网格单元格上特定设备的总数的一半,并将第一个单元格向右对齐,第二个向左对齐来实现。

因此对于您的具体情况,这意味着:

<div class="mdc-layout-grid">
  <div class="mdc-layout-grid__inner">
    <div class="mdc-layout-grid__cell mdc-layout-grid--align-right
      mdc-layout-grid__cell--span-6-desktop
      mdc-layout-grid__cell--span-4-tablet
      mdc-layout-grid__cell--span-2-phone">first</div>
    <div class="mdc-layout-grid__cell mdc-layout-grid--align-left
      mdc-layout-grid__cell--span-6-desktop
      mdc-layout-grid__cell--span-4-tablet
      mdc-layout-grid__cell--span-2-phone">second</div>
  </div>
</div>