詳細釐清 justify-content 與 justify-items 的差異與使用時機,並以實際案例來說明。
屬性名稱 作用對象 功能 常見應用於
justify-content 整個內容區塊 調整整組項目在主軸上的對齊方式 排列整體項目(像是多格)
justify-items 每個子項目 調整每個項目本身在主軸上的對齊 對齊格子中的內容
比較面向 justify-content justify-items
操作對象 多個子元素構成的一整排 每個子元素內部(或格子內部)內容的對齊方式
影響層級 針對整體容器(容器內子項的集合) 針對容器中每個子項目本身
搭配使用的容器 display: flex 或 display: grid 容器 主要是 display: grid 時有效
常見值 flex-start, center, space-between 等 start, center, end, stretch 等
justify-content:
→ 用來對齊多個項目的整體位置。
✅ 適合項目數量 > 1(如多個區塊排列)。
justify-items:
→ 用來設定每個項目內部對齊方式。
✅ 多用於 grid,針對每格中項目對齊。
❌ 在 flex 中通常不生效(要用 align-self)。
🔸 justify-content 範例(多格項目整體置中):
.container {
display: flex;
justify-content: center;
}
<div class="container">
<div>Box 1</div>
<div>Box 2</div>
</div>
➡️ 兩個 Box 被整體置中排列。
🔸 justify-items 範例(格子內部項目置中):
.grid {
display: grid;
grid-template-columns: repeat(2, 100px);
justify-items: center;
}
<div class="grid">
<div>Box A</div>
<div>Box B</div>
</div>
➡️ 每格內的文字都置中對齊。
❌ 「一個用 justify-content,多個用 justify-items」並不精確。
✅ 正確理解應是:
若想調整整組子元素的位置 → justify-content
若想調整每個子元素在格子內的對齊方式 → justify-items(通常用在 grid)