Add IE Conditionals to wp_enqueue_style

Posted on

When creating a WordPress theme, it’s best practice to use wp_enqueue_style for adding all stylesheets, including style.css. At first glance, this can pose a challenge if you want to conditionally include CSS based on the browser (like IE-only styles, for example). Luckily, there is a quick way to do this in WordPress using $wp-styles:

global $wp_styles;
wp_enqueue_style( 'jlc_ie_styles',get_template_directory_uri() . 'css/ie-style.css', array(), '1.0.0' );
$wp_styles->add_data( 'jlc_ie_styles', 'conditional', 'IE' );

The code above calls on the $wp-styles class to associate our IE-only stylesheet (by tag/name/slug) with a condition, the condition being “IE.” If you wanted IE 9 and below, you could do this:

$wp_styles->add_data( 'jlc_ie_styles', 'conditional', 'lte IE 9' );

This is a great (and best practice) way to conditionally call styles. You can see more examples with comments over in this gist by wpscholar.