Dexter Schneider
Dexter Schneider

Reputation: 2520

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

Upvotes: 2

Views: 946

Answers (2)

David Passmore
David Passmore

Reputation: 6099

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

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

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

is the right way to do it because you see this on many websites:

<!--[if IE9]>
<html class="ie9">
<![endif]-->

<!--[if IE8]>
<html class="ie8">
<![endif]-->

<!--[if lte IE7]>
<html class="ie7">
<![endif]-->

<!--[if !IE]><!-->
<html>
<!--<![endif]-->

content....

</html>

Upvotes: 1

BoltClock
BoltClock

Reputation: 724512

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]-->

Upvotes: 2

Related Questions