Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IE conditional comments inside a stylesheet

I know that you can use an IE conditional comment inside HTML:

<!--[if IE]>   <link href="ieOnlyStylesheet.css" /> <![endif]--> 

But what if I want to target only IE in a stylesheet, setting up a css rule for a specific element inside the html. For example, you can use this Chrome/Safari hack inside the css file as css code...

@media screen and (-webkit-min-device-pixel-ratio:0) {     .myClass{         background: #fff;         background:rgba(255,0,255,0.7);     } } 

But using the IE hack inside the CSS stylesheet like this:

 <!--[if IE]>       .myClass{         background: #fff;         background:rgba(255,0,255,0.7);     }  <![endif]--> 

does not work. What do I use inside a stylesheet to target IE only?

like image 891
Dexter Schneider Avatar asked Jul 28 '12 18:07

Dexter Schneider


People also ask

Can you use conditionals in CSS?

CSS Conditional Rules is a CSS module that allows to define a set of rules that will only apply based on the capabilities of the processor or the document the style sheet is being applied to.

What is conditional comments in HTML?

Conditional comments are conditional statements interpreted by Microsoft Internet Explorer versions 5 through 9 in HTML source code. They can be used to provide and hide code to and from these versions of Internet Explorer. Conditional comments are not supported in Internet Explorer 10 and 11.


2 Answers

Conditional comments do not work within stylesheets. Instead, you can use conditional comments in your HTML to apply different CSS classes or IDs to elements that you can then target with CSS.

For instance:

<!--[if IE]>   <div id="wrapper" class="ie"> <![endif]--> <!--[if !IE]>   <div id="wrapper"> <![endif]--> 

Also, there are tools such as Modernizr that do feature detection in a very similar way (by adding classes to the <html> element). You can use it to progressively enhance your design/script for newer browsers while still supporting older browsers.

like image 181
Derek Hunziker Avatar answered Oct 04 '22 10:10

Derek Hunziker


It can be easier than what Derek Hunziker said:

Simply include this code as it is:

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

Then you can target it easily, for example if you want to target IE 8 and lower you write:

.lt-ie9 body{css rule here;} 

and you are done!

Cheers

like image 35
Yannis Dran Avatar answered Oct 04 '22 10:10

Yannis Dran