Search code examples
htmlcssconditional-comments

Using Conditional Comments the right way


I want to know, when using conditional comments, what is the correct way (pay attention to the closing div tags)

This way, with one closing div for both conditional divs

<!--[if IE]>
<div id="IEdiv">
<![endif]-->

<!--[if !IE]><!-->
<div id="AllOtherDiv">
<!--<![endif]-->

  <div>The Content</div>
</div>

OR

This way, with a closing div for each conditional div, and repeating the SAME html

<!--[if IE]>
<div id="IEdiv">
<div>The Content</div>
</div> 
<![endif]-->

<!--[if !IE]><!-->
<div id="AllOtherDiv">
<!--<![endif]-->
<div>The Content</div>        
</div>

NOTE: You might wonder why I don't just use conditional stylesheets if the inner HTML is the same, but I use inline styles on the conditional divs(I have to) and the inline style for IE is different (necessary because IE sucks so bad with it's css support... )

Thank you


Solution

  • Neither is technically right or wrong, but repeating the contents seems quite a waste if it's going to be the same across browsers. Just conditionalize the start tag as in your first example. HTML comments are designed to allow such a technique.

    HTML5 Boilerplate happens to do this with the <html> start tag, by the way, except with classes and slightly different conditional comments, but you can use any attribute you want as long as you target browsers correctly:

    <!--[if lt IE 7]> <html lang="en-us" class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
    <!--[if IE 7]>    <html lang="en-us" class="no-js lt-ie9 lt-ie8"> <![endif]-->
    <!--[if IE 8]>    <html lang="en-us" class="no-js lt-ie9"> <![endif]-->
    <!--[if gt IE 8]><!--> <html lang="en-us" class="no-js"> <!--<![endif]-->