條件註釋是微軟自 IE5 起提供的私有功能,讓你能用註釋語法為不同版本的 IE 指定不同的內容或樣式。它最大的優點是安全:寫在註釋裡的程式碼不會被其他瀏覽器執行,也不會通過 W3C 驗證的檢查。
<!--[if IE]> 所有 Windows 上的 IE 可識別 <![endif]--> <!--[if IE 5.0]> 只有 IE5.0 可識別 <![endif]--> <!--[if lt IE 6]> IE6 以前(含)可識別 <![endif]--> <!--[if lte IE 6]> IE6 及更低版本 <![endif]--> <!--[if gte IE 6]> IE6 及更高版本 <![endif]--> <!--[if gt IE 6]> 高於 IE6 的版本 <![endif]--> <!--[if IE 7]> 僅 IE7 <![endif]--> <!--[if lte IE 7]> IE7 及更低版本 <![endif]--> <!--[if gte IE 7]> IE7 及更高版本 <![endif]--> <!--[if IE 8]> 僅 IE8 <![endif]--> <!--[if IE 9]> 僅 IE9 <![endif]-->
四個運算子的意義:
| 寫法 | 意義 |
|---|---|
| IE 8 | 等於 IE8,僅 IE8 可識別 |
| lt IE 8 | less than,IE7 或更低版本 |
| gt IE 8 | greater than,高於 IE8 的版本 |
| lte IE 8 | less than or equal,IE8 及更低版本 |
| gte IE 8 | greater than or equal,IE8 及更高版本 |
還有一個實用上很關鍵的寫法,用來排除 IE:
<!--[if !IE]>除 IE 外都可識別<![endif]-->
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>DIV 條件註釋實例</title> </head> <body> 你正在使用: <!--[if IE 6]><h2>IE6</h2><![endif]--> <!--[if IE 7]><h2>IE7</h2><![endif]--> <!--[if IE 8]><h2>IE8</h2><![endif]--> <!--[if IE 9]><h2>IE9</h2><![endif]--> </body> </html>
用對應版本的 IE 打開,頁面就會顯示該版本的名稱;用其他瀏覽器打開則完全不顯示任何一行。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CSS 條件註釋 hack 實例</title>
<!--[if IE 6]>
<style type="text/css">.divcss{ color:#F00;}</style>
<![endif]-->
<!--[if IE 7]>
<style type="text/css">.divcss{ color:#FF0;}</style>
<![endif]-->
<!--[if IE 8]>
<style type="text/css">.divcss{ color:#00F;}</style>
<![endif]-->
<!--[if IE 9]>
<style type="text/css">.divcss{ color:#000;}</style>
<![endif]-->
</head>
<body>
<div class="divcss">
這段文字在 IE6 下是紅色、IE7 下是黃色、IE8 下是藍色、IE9 下是黑色。
</div>
</body>
</html>
條件註釋最合適的用法是載入獨立的修正樣式表,而不是在頁面裡塞入多組 <style>:
<!--[if lt IE 9]> <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]-->
這樣做的好處是主樣式表保持乾淨,舊版修正集中在一個檔案裡,日後要淘汰 IE 支援時只要刪掉那一行註釋即可。
另外提醒,條件註釋是 IE10 以後正式停止支援的功能。IE10 及之後的版本會完全忽略這些語法,因此它只能作為處理 IE9 以下的手段;IE10/11 的相容問題得改用 @media hack 或特性偵測來處理。