先看一個常見誤解。下面兩條規則,最後生效的其實是寫在前面的 16px:
<style type="text/css">
div.ui_infor p { font-size: 16px; }
.ui_infor p { font-size: 14px; }
</style>
<div class="ui_infor"><p>test of css</p></div>
原因在於權重計算,並不是「後寫就贏」。
把權重想成一組 0,0,0,0 的數字,從左到右依序累加:
<p style="font-size:14px;">#demo {}.demo {}、偽類 :hover、屬性選擇器 [rel="xx"]p {}回到上面的例子:div.ui_infor p 是 0,0,1,2;.ui_infor p 是 0,0,1,1。前者較大,所以 16px 勝出。
網上常說 IE6 不支援 !important,其實不準確。看這段:
p { font-size: 18px !important; font-size: 12px; }
在 IE6 中會顯示 12px。但改成寫成兩條規則:
p { font-size: 18px !important; }
p { font-size: 12px; }
IE6 就會正確顯示 18px。可見 IE6 認得 !important,只是有個怪癖:寫在同一條規則內的同名屬性,後者會把帶 !important 的前者蓋掉。
把這個 bug 反過來利用,就能在不寫 CSS hack 的情況下模擬 min-height:
p { min-height: 50px; height: auto !important; height: 50px; }
標準瀏覽器讀到 height:auto !important 會採用它,IE6 則因上述怪癖採用最後的 50px,剛好對應 min-height 的效果。