在做網頁版面時,「讓好幾個方塊並排後整體居中」是很常見的需求。單靠屬性硬寫往往會在不同瀏覽器下走樣,但只要善用 display: table 與 inline-block,再搭配各瀏覽器的相容寫法,就能優雅地解決這個問題。
做法是替最外層容器設 text-align: center,並讓內層方塊以類似表格單元格的方式排列。由於各瀏覽器對 display 的支援不一,需要分別針對 IE、Mozilla、Opera 給出對應的規則。
body { text-align: center; }
#outer { width: 60%; background: #ffffcc; margin: auto; text-align: center; }
.inner { width: 100px; height: 100px; margin: 5px; border: 1px solid #000; }
* html .inner { display: inline; } /* for IE */
html>body #outer { display: table; } /* for mozilla */
html>body .inner { display: table; float: left; } /* for mozilla */
@media all and (min-width: 0px){ /* Opera 7 */
html>body .inner { display: inline-block; float: none; }
}
把多個 class="inner" 的方塊放進 id 為 outer 的容器中,並在最後加上一個清除浮動的元素 <br style="clear:both" />,就能確保並排的方塊整體居中、換行時整齊對齊。這種做法的優點是完全不依賴固定寬度,方塊數量增減都能自動適應,是早期追求跨瀏覽器相容版面時相當經典的技巧。