需求:固定寬容器內,多個子元素水平排列、整體置中、且等分剩餘空間。早期提議的 box-align: center 從未標準化,現代用 Flex/Grid 輕鬆實現。本文對比傳統 float 痛點與現代最佳解法。
.container { width: 800px; }
.item { float: left; width: 150px; margin: 0 20px; }
問題:
display: inline).container {
display: flex;
justify-content: space-between; /* 兩端對齊,項目間等距 */
/* 或 */
justify-content: space-around; /* 項目兩側等距,邊緣半距 */
/* 或 */
justify-content: space-evenly; /* 所有間隙完全相等 */
align-items: center; /* 垂直置中 */
gap: 20px; /* 明確間距(現代瀏覽器) */
}
.item { width: 150px; } /* 固寬,或 flex: 1 等寬 */
.container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
justify-content: center; /* 整體置中 */
gap: 20px;
align-items: center;
}
auto-fit + minmax() 實現響應式列數自動調整,無需媒體查詢。
.container {
display: -ms-flexbox;
-ms-flex-pack: justify; /* justify-content: space-between */
-ms-flex-align: center;
display: flex;
justify-content: space-between;
align-items: center;
}
.container { text-align: center; font-size: 0; /* 消除間隙 */ }
.item { display: inline-block; width: 150px; font-size: 16px; vertical-align: top; }
/* 間距靠 margin 或 父層 letter-spacing/word-spacing 控制,較麻煩 */
box-align 來自舊版 Flexbox 草案(2009),僅 Firefox 早期版本以 -moz-box-align 實現。現代標準為 align-items(交叉軸對齊)與 justify-content(主軸對齊)。
.product-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 24px;
padding: 24px;
justify-content: center; /* 最後一行不滿時整體置中 */
}
.product-card {
background: #fff; border-radius: 8px; overflow: hidden;
box-shadow: 0 2px 8px rgba(0,0,0,.08);
transition: transform .2s, box-shadow .2s;
}
.product-card:hover { transform: translateY(-4px); box-shadow: 0 8px 24px rgba(0,0,0,.12); }
box-align 早已成為歷史。Flexbox 的 justify-content: space-between/around/evenly 與 Grid 的 auto-fit/minmax 是解決多元素等距置中的現代標準答案。新專案請直接採用,舊專案重構時優先替換 float 佈局。