寫 CSS 時,只要在樣式表加上瀏覽器標識符,就能讓同一條屬性在不同瀏覽器上呈現不同結果。以下是各家瀏覽器對這些標識符的識別能力:
*,標準瀏覽器(如 Firefox)不能識別 *。*,但不能識別 !important。*,也能識別 !important。\0,但不能識別 *、+、_、*加!important。*,但能識別 !important。例如 style="*width:10px!important; width:20px;":在 IE6 下寬度為 10px,在 IE7 下則為 20px。
寫法一
width:100px; /* Firefox 及其他瀏覽器 */ width:200px\0; /* IE8 能識別 \0 */ *width:300px!important; /* IE7 同時識別 * 與 !important */ *width:400px; /* IE6 也能識別 * */ /* 注意順序 */
寫法二
width:100px; /* Firefox 及其他瀏覽器 */ width:200px\0; /* IE8 能識別 \0 */ *width:300px; /* IE7 也能識別 * */ _width:400px; /* IE6 能識別下劃線 */ /* 注意順序 */
寫法三
width:100px; /* Firefox 及其他瀏覽器 */ width:200px\0; /* IE8 能識別 \0 */ +width:300px; /* + 只被 IE7 識別 */ _width:400px; /* IE6 能識別下劃線 */ /* 注意順序 */
三種寫法的共同重點是順序:由於 CSS 採用後宣告覆蓋先宣告,因此必須把通用寫法放最上面,特殊寫法依序往下疊。
/* 1 */ .color1{ color:#F00; color/*\**/:#00F /*\**/}
/* IE6,IE7,IE8,FF,OP,SA 都識別 */
/* 2 */ .color2{ color:#F00; color /*\**/:#00F /*\9**/}
/* IE7,IE8,FF,OP,SA 識別 */
/* 3 */ .color3{ color:#F00; color/*\**/:#00F \9}
/* IE6,IE7,IE8 識別 */
/* 4 */ .color4{ color:#F00; color /*\**/:#00F\9}
/* IE7,IE8 識別(color 與 /*\**/ 之間必須有空格) */
其中 OP 代表 Opera,SA 代表 Safari。
width:100px\0; /* IE8 */ _width:100px; /* IE6 */ [width:100px; /* IE6, IE7 */ +width:100px; /* IE6, IE7 */ *width:100px; /* IE6, IE7 */ *width:100px!important; /* IE6, IE7 */ *+width:100px; /* IE6, IE7 */ *+width:100px!important; /* IE6, IE7 */ width:100px\9; /* IE6, IE7, IE8 */ width:100px!important; /* IE6, IE7, IE8, FF */ w\idth:100px; /* IE5.x 不支援;IE6、IE7、IE8、FF 支援 */
條件註解是比 hack 更乾淨、也更可靠的分流方式,建議優先採用:
<!--[if IE]>此內容只有 IE 可見<![endif]--> <!--[if IE 6.0]>此內容只有 IE6.0 可見<![endif]--> <!--[if IE 7.0]>此內容只有 IE7.0 可見<![endif]-->
實務建議:hack 只是過渡手段。能用特性偵測或條件註解解決的,就不要把 hack 寫進主樣式表;否則樣式表很快就會變成一張誰也不敢碰的符碼圖。