Hidden browser gems – Part II: conditional comments
Browser, Hidden Browser Gems October 20th, 2007The Internet Explorer has the nice ability to detect specially formatted HTML comments and recognize them as programmable conditions. While all other browsers are treating them as regularly HTML comments, they will ignore the conditions and its branches completely.
Thus we have a great possibility to address Internet Explorer browsers in a valid, standard-compliant way without using a client or server side scripting language.
Generally conditions start with [if] and end with [endif]:
<!--[if exp]> HTML block <![endif]-->
The typically use of this technique to figure out which version of Internet Explorer the client is using. An expression can contain the string IE, the version number, comparison operators (lt, lte, gt, gte), boolean operators (&, |, !) and parentheses ((, )).
With this constituents it is possible to construct flexible version number detections.
<!--[if IE]> <link rel="stylesheet" href="styles_ie.css" type="text/css"> <[endif]-->
It is even possible to nest comments.
<!--[if IE]> <![if gte IE 5]> <link rel="stylesheet" href="styles_ie5.css" type="text/css"> <![endif]> <![if (gt IE 5)&(lt IE 7) ]> <link rel="stylesheet" href="styles_ie55_and6.css" type="text/css"> <![endif]> <![if IE 7]> <link rel="stylesheet" href="styles_ie7_hacks.css" type="text/css"> <![endif]> <![endif]-->