2012年2月22日

[CSS] 用 CSS hack 或分離 IE-only 的樣式表

1. 直接使用CSS hack:
CSS hack for IE6 - IE9,請參考以下語法及順序:
p.sample {color:#000;}
p.sample {color:#de00ff \9;} /* for IE8&9 */
p.sample {color:#0080ff \0/;} /* for IE9 */
p.sample {*color:#00ff1e;} /* for IE7 前面加星號 */
p.sample {_color:#ffb400;} /* for IE6 前面加底線 */
P.S. 請留意 \9 及 \0/ 前的空格不要省略

for IE9 的另一種寫法:
:root p.sample {color:#0080ff \0/;}
這種寫法的CSS優先度較高,可放在 \9 行之前,不過前面要多一個無意義的 :root。

2. 將IE-only的CSS與正常CSS分離:
另一種方式是將IE-only的CSS與正常CSS分離為不同檔案,由於在IE-only的css檔中也可搭配上述的CSS hack,且可保持正常CSS檔的整潔,因此特別推薦使用! (載入額外的CSS檔會增加HTTP Request次數,如果很在意此點就另當別論)
寫法如下,在<head>中增加條件判斷式:

for IE9以上
<!--[if gte IE 9]>
<link rel="stylesheet" href="css/ie.css" />
<![endif]-->

for IE8以下
<!--[if lte IE 8]>
<link rel="stylesheet" href="css/ie8.css" />
<![endif]-->

說明:
gt: greater than (版本號大於)
lt: less than (版本號小於)
gte: greater than or equal to (版本號大於等於)
lte: less than or equal to (版本號小於等於)
詳細的使用範例請參考:
How To Create an IE-Only Stylesheet
http://css-tricks.com/how-to-create-an-ie-only-stylesheet/

延伸閱讀:
In defense of CSS hacks — introducing “safe CSS hacks”
http://mathiasbynens.be/notes/safe-css-hacks

沒有留言:

張貼留言

關於我