把內容並排成好幾欄,是版型上最基礎也最高頻的需求。以下整理四種傳統做法,並補上今天更值得使用的 Grid 與 Flexbox。
借用表格的排列語意,但不真的寫 <table>。最大的優點是各欄自動等高,且不需要清除浮動。
<style>
.table {
width: auto;
min-width: 1000px;
margin: 0 auto;
padding: 0;
display: table;
}
.tableRow { display: table-row; }
.tableCell {
border: 1px solid red;
display: table-cell;
width: 33%;
}
</style>
<div class="table">
<div class="tableRow">
<div class="tableCell">one</div>
<div class="tableCell">two</div>
<div class="tableCell">three</div>
</div>
</div>
注意:table-cell 元素無法設定 margin,間距要靠 border-spacing 或內層 padding 處理。
最經典的寫法,相容性最好,但需要清除浮動。
<style>
.row {
float: left;
width: 33%;
border: 1px solid red;
}
.clear { clear: both; }
</style>
<div class="row">one</div>
<div class="row">two</div>
<div class="row">three</div>
<div class="clear"></div>
坑:三欄各 33% 加上 border 會超過 100% 導致換行,需改用 box-sizing: border-box 或把寬度調成 32%。
寫法直覺,但會有兩個經典陷阱。
<style>
.row {
display: inline-block;
width: 32%;
border: 1px solid red;
}
</style>
<div class="row">one</div>
<div class="row">two</div>
<div class="row">three</div>
陷阱一:HTML 標籤之間的空白會被渲染成一個空格寬度,導致三欄擠不下而換行。解法是把標籤寫在同一行、用註解填掉空白,或把父層 font-size 設為 0 再於子元素還原。
陷阱二:需要處理 IE6/7 的 *display: inline; *zoom: 1; hack 才能觸發 inline-block 行為。
前三種是「並排的區塊」,而 CSS Multi-column 是「讓內容像報紙一樣自動流動到下一欄」,用途不同——適合長篇文章,不適合需要精細控制的卡片排列。
<style>
.column {
-moz-column-count: 3; /* Firefox */
-webkit-column-count: 3; /* Safari / Chrome */
column-count: 3;
-moz-column-gap: 40px;
-webkit-column-gap: 40px;
column-gap: 40px;
-moz-column-rule: 4px outset #ff0000;
-webkit-column-rule: 4px outset #ff0000;
column-rule: 4px outset #ff0000;
}
</style>
<div class="column">
<p>文章內容會自動分配到三欄…</p>
</div>
還可用 column-width 讓瀏覽器依可用寬度自動決定欄數,或用 column-span: all 讓標題跨滿所有欄。
以上四種都有各自的歷史定位,但現代專案請直接用 Grid:
/* 等寬三欄,間距 20px,各欄自動等高 */
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 20px;
}
/* RWD:卡片寬度不低於 240px 時自動決定欄數 */
.auto-fit {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 16px;
}
最後那段 auto-fit + minmax() 是現代響應式網格的核心技巧,取代了过去一大堆 media query。
Flexbox 則適合單軸排列(例如導覽列、需要 wrap 的標籤群):
.flex {
display: flex;
flex-wrap: wrap;
gap: 16px;
}
.flex > * { flex: 1 1 240px; }
兩者最大的好處:不需要清除浮動、不需要 box-sizing 修正、間距用 gap 一行搞定、各項預設自動等高。上面程式碼在 Chrome、Firefox、Safari、Edge 皆一致運作,前綴已可全部省略。