網格包裝器

網格包裝器模式在將網格內容對齊到中心包裝器內的同時,還允許專案突破並對齊到其包含元素或頁面的邊緣,這非常有用。

依賴項

放置在網格上的專案應該能夠對齊到水平居中的最大寬度包裝器或網格的外邊緣,或兩者兼而有之。

示例

點選下面程式碼塊中的“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 網格佈局和可訪問性)。

另見