介紹
在卡片佈局中跨列對齊嵌套元件是響應式網頁設計中常見的佈局挑戰。
雖然 CSS Grid 和 Flexbox 可以輕鬆均衡同級卡片容器的高度,但對齊內部元素(例如標題、正文和 CTA 按鈕)仍然很困難。如果一張卡片具有多行標題,而另一張卡片具有單行標題,則以下元素將錯位,從而導致 UI 不一致。
CSS 網格子網格 功能解決了此佈局限制。本指南解釋了 subgrid 的工作原理並分享了建立對齊網格卡的樣式策略。
1. 嵌套 CSS 網格的局限性
讓我們看看在不使用 subgrid 參數的情況下對齊巢狀元素的限制。
HTML結構
<div class="grid-container">
<div class="card">
<h3 class="card-title">Short Title</h3>
<p class="card-desc">Short description text.</p>
<button class="card-btn">Read More</button>
</div>
<div class="card">
<h3 class="card-title">Extremely Long and Complex Multi-line Card Title</h3>
<p class="card-desc">This card contains long body copy that wraps across multiple lines.</p>
<button class="card-btn">Read More</button>
</div>
</div>
傳統的 Flexbox/Grid 解決方法
.grid-container {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 20px;
}
.card {
display: flex;
flex-direction: column;
justify-content: space-between; /* Pushes button to bottom */
}
- 問題: 卡片容器本身對齊到相同的高度,並且按鈕位於底部。但是,標題的下緣和描述段落的開頭沒有對齊。由於一個標題較長,因此其下方的描述文字開始位置低於相鄰卡片中的描述,從而破壞了佈局一致性。
2. 解決子網格的對齊問題
使用 subgrid,巢狀網格容器繼承在其父網格容器上定義的行和列軌道。
這意味著同級卡元素可以共享相同的網格軌道定義。所有卡片上的標題共用一個網格行,描述文字區塊共用另一個網格行,將它們完美對齊。
子網格 CSS 實現
/* 1. Define the grid tracks, including nested rows, on the parent container */
.grid-container {
display: grid;
grid-template-columns: repeat(2, 1fr);
/* The parent container handles rows dynamically */
gap: 20px;
}
/* 2. Configure the card to inherit parent row alignments using subgrid */
.card {
display: grid;
/* Tell the card to inherit parent row definitions */
grid-template-rows: subgrid;
/* Instruct the card to span 3 rows defined on the parent grid */
grid-row: span 3;
gap: 10px;
background: #f9f9f9;
padding: 15px;
border-radius: 8px;
}
/* 3. Assign internal items to specific rows */
.card-title {
grid-row: 1; /* Row 1 */
}
.card-desc {
grid-row: 2; /* Row 2 */
}
.card-btn {
grid-row: 3; /* Row 3 */
}
為什麼這有效
設定 grid-template-rows: subgrid 指示每個 .card 將其內部元素直接與父網格容器的行對齊。
第 1 行(標題行)的高度自動擴展以適合該行中最高的卡片標題。這可確保第 2 行中的描述以完全相同的垂直對齊方式開始,無論標題長度為何。
3. 水平列對齊範例
您也可以水平套用 subgrid 來對齊列軌道。
例如,在建立表單時,即使標籤的文字長度不同,您也可以跨多行對齊標籤和輸入欄位。
.form-row {
display: grid;
grid-template-columns: subgrid; /* Inherits the parent grid column proportions */
grid-column: span 2;
}
這會將所有輸入欄位水平跨行對齊,而無需您定義標籤元素的硬編碼寬度。
結論和瀏覽器支持
CSS Grid subgrid 完全支援所有現代瀏覽器,包括 Safari、Firefox、Chrome 和 Edge。
實作 subgrid 消除了基於 JavaScript 的高度匹配和複雜的 Flexbox 邊距的需要。
在版面配置中使用 subgrid 來對齊巢狀元件並提高卡片設計的一致性。

