Enqueue different stylesheets using IE conditionals

While basic use of CSS IE conditionals is off-topic for WPSE, WordPress does include a method for enqueueing stylesheets conditionally, based on CSS IE conditionals.

First, you need to use the correct conditionals:

<!--[if lt IE 9]>  ie.css <![endif]-->

Second, you should enqueue this stylesheet properly, in functions.php, via callback hooked into wp_enqueue_scripts:

<?php
function wpse48581_enqueue_ie_css() {
    // Register stylesheet
    wp_register_style( 'wpse45851-ie', get_template_directory_uri() . '/css/ie.css' );
    // Apply IE conditionals
    $GLOBALS['wp_styles']->add_data( 'wpse45851-ie', 'conditional', 'lt IE 9' );
    // Enqueue stylesheet
    wp_enqueue_style( 'wpse45851-ie' );
}
add_action( 'wp_enqueue_scripts', 'wpse48581_enqueue_ie_css' );
?>

Edit

Based on this comment:

But I only want to use ie.css on IE less than IE9 and style.css for IE9 and non-IE browser

This is actually a non-standard way of defining stylesheets for IE support, because it completely circumvents the cascading part of CSS. Nevertheless, it is entirely possible. Simply use the above method to enqueue style.css also, using the appropriate conditionals. For example, this may not be the best approach, but it will work:

<?php
function wpse48581_enqueue_ie_css() {
    // Register and enqueue lt IE9 stylesheet
    wp_register_style( 'wpse45851-ie', get_template_directory_uri() . '/css/ie.css' );
    $GLOBALS['wp_styles']->add_data( 'wpse45851-ie', 'conditional', 'lt IE 9' );
    wp_enqueue_style( 'wpse45851-ie' );
    // Register and enqueue IE9 stylesheet
    wp_register_style( 'wpse45851-ie9', get_template_directory_uri() . '/style.css' );
    $GLOBALS['wp_styles']->add_data( 'wpse45851-ie9', 'conditional', 'IE 9' );
    wp_enqueue_style( 'wpse45851-ie9' );
    // Register and enqueue default stylesheet
    // Note that we use the SAME style.css as above
    wp_register_style( 'wpse45851-default', get_template_directory_uri() . '/style.css' );
    $GLOBALS['wp_styles']->add_data( 'wpse45851-default', 'conditional', '!IE' );
    wp_enqueue_style( 'wpse45851-default' );
}
add_action( 'wp_enqueue_scripts', 'wpse48581_enqueue_ie_css' );
?>

Caveat: this will work, but I strongly recommend that you reconsider your approach to your IE-specific style declarations. Your life will be much easier if you always use your default stylesheet, and then take advantage of the cascade to override the default, where necessary.

Leave a Comment