多欄排版是頁面上最基礎的需求之一。同一個「三欄並排」的效果,至少有四種寫法,各自的相容性、行為特性與適用時機都不太一樣。以下逐一實作並比較。
把 div 偽裝成表格,讓瀏覽器用表格演算法排版。最大的優點是欄高會自動對齊——最高的那一欄撐起整排,不必用 JS 補齊。
<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>
最經典的做法,也是支撐了整個 2005–2012 年網路版面的技術。缺點是父容器會塌陷(高度變成 0),必須靠 clearfix 收尾。
<style>
.row {
float: left;
width: 33%;
border: 1px solid red;
}
/* 別忘了清除浮動 */
.row::after {
content: "";
display: table;
clear: both;
}
</style>
<div class="row">one</div>
<div class="row">two</div>
<div class="row">three</div>
寫法最直觀,元素像文字一樣並排。但要注意兩個坑:一是 HTML 之間的空白會產生約 4px 的間隙,二是垂直對齊預設為 baseline,導致各欄底部不齊。
<style>
.row {
display: inline-block;
width: 32%; /* 留一點餘裕給空白產生的間隙 */
border: 1px solid red;
vertical-align: top; /* 讓各欄頂端對齊 */
}
</style>
<div class="row">one</div>
<div class="row">two</div>
<div class="row">three</div>
這是 CSS 唯一「原生」的多欄方案:只要指定欄數,瀏覽器會自動把內容平均分配到各欄,像報紙排版一樣。適合的是「文字流動式分欄」,而不是「幾個並排的區塊」。
<style>
.column {
/* 欄數 */
-moz-column-count: 3; /* Firefox */
-webkit-column-count: 3; /* Safari and 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"></div>
以上四種在示範中都是在 Chrome 上實測,使用前請自行確認相容性。但更實際的建議是:如果是新專案,前四種都可以不用了。
用 Flexbox(display: flex)——若你要的是「一維排列」,也就是一排並排的區塊:
.row {
display: flex;
gap: 40px; /* 直接取代 margin 與 width 計算 */
}
.row > * {
flex: 1; /* 自動均分,不必寫 33% */
}
它一次解決了 float 的塌陷、inline-block 的空白間隙、table 的語意混淆三個問題,而且不必算寬度。
用 Grid(display: grid)——若你要的是「二維排列」,同時需要控制列與欄:
.row {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 40px;
}
column-count 則仍然保有它的位置:當你有一段長文字要像報紙那樣自動流式分欄時,它是唯一合適的工具,Flexbox 與 Grid 都做不到這件事。
最後一點值得強調:display: table 這個技巧之所以流行,是因為在沒有 Flexbox 的年代需要「欄高對齊」。如今這已是 Flexbox 與 Grid 的預設行為,而它帶來的副作用(HTML 語意上宣告為表格、實際卻不是表格資料)反而是維護上的負擔。