萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 多個子元素等距置中:box-align 替代方案與現代 Flex/Grid 實現

前言

需求:固定寬容器內,多個子元素水平排列、整體置中、且等分剩餘空間。早期提議的 box-align: center 從未標準化,現代用 Flex/Grid 輕鬆實現。本文對比傳統 float 痛點與現代最佳解法。

一、傳統 Float 方案痛點

.container { width: 800px; }
.item { float: left; width: 150px; margin: 0 20px; }

問題:

  • IE6 雙倍 margin bug(需 display: inline)
  • 間距手動計算,項目增減需改 CSS
  • 容器寬度變化時,間距不自動調整
  • 需額外清除浮動

二、現代最佳方案:Flexbox

.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 等寬 */

三、Grid 方案(二維佈局更強)

.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  justify-content: center; /* 整體置中 */
  gap: 20px;
  align-items: center;
}

auto-fit + minmax() 實現響應式列數自動調整,無需媒體查詢。

四、舊瀏覽器相容方案(IE10+)

Flex 舊語法(IE10 -ms- 前綴)

.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;
}

Inline-block + text-align: center(IE8+)

.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 歷史背景

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 佈局。

copyright © 萬盛學電腦網 all rights reserved