WordPress and Conditional Comment CSS

Posted on Monday, June 29th, 2009 at 4:54 pm in

Conditional comments provide a way of serving specific content to various versions of Internet Explorer — from IE 5 upwards.

The Benefits

Conditional comments can be used to serve additional, version-specific, CSS to IE browsers — allowing you to deal with inconsistent displays in earlier IE versions in a way that doesn’t impact on the display in the better browsers.

Unlike CSS hacks, conditional comments won’t “bite back” every time a new version of IE is released. And they also offer version-targetting that is extremely difficult to achieve using standard hacks.

Conditional Comment Syntax

The basic syntax of a conditional comment is:

<!--[if condition]>
(what to output if the condition is true)
<![endif]-->

Specific Examples

<!--[if IE]>[...]<![endif]-->
If the browser is Internet Explorer (any version)

<!--[if IE 7]>[...]<![endif]-->
If the browser is Internet Explorer 7

<!--[if lt IE 7]>[...]<![endif]-->
If the browser is less than Internet Explorer 7

<!--[if lte IE 7]>[...]<![endif]-->
If the browser is less than, or equal to, Internet Explorer 7

<!--[if gte IE 6]>[...]<![endif]-->
If the browser is greater than, or equal to, Internet Explorer 6

<!--[if gt IE 6]>[...]<![endif]-->
If the browser is greater than Internet Explorer 6

Additional Style Sheet For All Versions of IE

<!--[if IE]>
<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/ie.css" media="screen" type="text/css" />
<![endif]-->

Additional Style Sheet For IE7 And Earlier

<!--[if lte IE 7]>
<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/ie7.css" media="screen" type="text/css" />
<![endif]-->

Serving Up IE Specific Javascript

<!--[if lte IE 7]>
<script src="<?php bloginfo('template_directory'); ?>/focus.js" type="text/javascript"></script>
<![endif]-->

Using with WordPress Themes

Add the appropriate conditional comment to your theme’s header.php file immediately after the call to the theme’s default stylesheet.

<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />
<!--[if IE 7]>
<link rel="stylesheet" href="<?php bloginfo('template_directory'); ?>/ie7.css" media="screen" type="text/css" />
<![endif]-->

Then upload your new IE-specific stylesheet (ie7.css in the example above) to your theme folder. You can now make changes to this new stylesheet and review the changes in IE without worrying about the impact on other browsers.

Happy commenting!

You might also be interested in

WordPress CMS and Blog Themes from £19.95

Top