YUI 的 Grids CSS 是一套相當經典的栅格布局方案,其中有幾個設計思路特別值得我們深入研究和借鑒。
一、以「負 margin」實現流動布局
它最核心的布局思想,是利用負邊距(Negative Margins)來構造流動式(Liquid)的多欄結構。想深入了解的讀者,可以參考《Creating Liquid Layouts with Negative Margins》一文。
二、以 em 為單位,讓寬度隨字體伸縮
當使用者調整瀏覽器的字體大小時,整個布局的寬度也能同步變化,這正是 em 單位的妙處。一個實用技巧是:以 13 像素為基準來均分寬度(小數保留到千分位),而 IE 瀏覽器則採用 13.333。
/* 750 centered, and backward compatibility */
#doc {
width:57.69em;
*width:56.251em;
min-width:750px;
}
補充說明:《Setting Page Width with YUI Grids》中提到,IE 下的 em 是寬度除以 13,再乘以 0.9759 得出。這也解釋了為何早期 YUI 源碼中 IE 下 750px 對應的寬度是 56.301em(750 / 13 * 0.9759)。而這套算法在 YUI 的後續版本中,將改為上文所述的新算法(IE 瀏覽器改用 13.333)。
三、清除布局中的浮動
針對非 IE 瀏覽器,採用 :after 偽元素的方式:
.yui-gf:after {
content:".";
display:block;
height:0;
clear:both;
visibility:hidden;
}
而對於 IE 瀏覽器,則使用 zoom:1 來觸發 haslayout。關於這一點,Nate Koechley 這樣解釋:
Zoom is a non-valid attribute and so you'll see warnings when you validate your CSS. I'm aware of that and think it is an acceptable tradeoff.
個人十分認同他的取捨觀點:I think it is an acceptable tradeoff。在兼容與規範之間,這是一種務實而聰明的平衡。