Those. conditional comments need explanation

The following code is designed to reliably detect the version of IE in the browser.

<!--[if lt IE 7 ]><body class="ie_6"><![endif]--> <!--[if IE 7 ]><body class="ie_7"><![endif]--> <!--[if IE 8 ]><body class="ie_8"><![endif]--> <!--[if IE 9 ]><body class="ie_9"><![endif]--> <!--[if (gt IE 9)|!(IE)]><!--> <body> <!--<![endif]--> 

I do not understand why this works. Why the regular <body> did not overwrite <body class="ie_9"> , since it is a regular tag, it should be recognized by all browsers.

What magic about

  <!--> <body> <!-- 
+6
source share
2 answers

You probably want to change !(IE) to (!IE)

In addition, the "normal" <body> tag you are talking about is in the conditional comment. The fact that it does not matter on another line is still inside the conditional comment tag, so it is affected as such.

Conditional comments for IE work using regular HTML comments <!-- --> , so any code inside the "false" conditional code is simply commented out; <!-- <body class="ie6"> --> IE then has its own syntax inside this. Thus, non-IE browsers just see the commented-out line, and IE sees it as an instruction to execute.

Because of this, only one body tag is displayed, and only one is used.


More explanation

 <!--[if (gt IE 9)|!(IE)]><!--> <body> <!--<![endif]--> 

In IE, it says:

 <if greater than ie9, or not ie> (ie conditional comment) <!--> (empty comment) (--> putting this here to stop SO ruining syntax highlighting :D) <body> <end if> (ie conditional comment) 

If you do not understand why, read the paragraph beginning with "Conditional comments for IE ...".

The same block for any other browser looks like this:

 <!--[if (gt IE 9)|!(IE)]><!--> (this is just one comment, containing the text "[if (gt IE 9)|!(IE)]><!") <body> <!--<![endif]--> (again, just one comment, containing "<![endif]") 
+11
source
 <!--[if (gt IE 9)|!(IE)]><!--> <body> <!--<![endif]--> 

means: output <body> there if the browser version is larger than ( gt ) IE9 (for example, IE10), or if it is not IE.

Since IE9 is currently the latest version, this condition is not met by any IE.

The trick is that --> in the first line closes the comment in other browsers, so for them <!--[if (gt IE 9)|!(IE)]><!--> is just a normal comment (same the most for <!-- in the last line).

But IE will parse <!--[if (gt IE 9)|!(IE)]> and <![endif]--> and consider <!--><body><!-- as the contents of a conditional comment. This means that if the condition is met, it displays an empty comment, the <body> and the beginning of the comment.

MSDN contains a detailed description of conditional comments . It seems you could achieve the same using the Conditional Comments levels below:

 <![if (gt IE 9)|!(IE)]> <p>Please upgrade to Internet Explorer version 8.</p> <![endif]> 

(although it is not valid HTML).

+3
source

Source: https://habr.com/ru/post/896949/


All Articles