How can I have special CSS for IE?

2020-06-19 07:38发布

问题:

I would like to use some different CSS for ie8 but keep just the one CSS file. Can anyone tell me what the best "hack" for this is? Yeah I know hacks are not good but I would like to keep one CSS file at least just for now.

For example, in non-IE8 browsers I would like the browser to see this:

div.content_header_heading { 
    background: -moz-linear-gradient(top, #cccccc 0%, #eeeeee 35%, #eeeeee 65%, #cccccc 100%); /* FF3.6+ */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#cccccc), color-stop(35%,#eeeeee), color-stop(65%,#eeeeee), color-stop(100%,#cccccc)); /* Chrome,Safari4+ */
    background: -webkit-linear-gradient(top, #cccccc 0%,#eeeeee 35%,#eeeeee 65%,#cccccc 100%); /* Chrome10+,Safari5.1+ */
    background: -o-linear-gradient(top, #cccccc 0%,#eeeeee 35%,#eeeeee 65%,#cccccc 100%); /* Opera11.10+ */
    background: -ms-linear-gradient(top, #cccccc 0%,#eeeeee 35%,#eeeeee 65%,#cccccc 100%); /* IE10+ */
}

But if the browser is IE8, I would like the browser to see this:

div.content_header_heading { 
}

回答1:

Paul Irish has a good solution to this problem. It involves using conditional comments to place classes on the <html> tag:

<!--[if lt IE 7 ]> <html class="ie6"> <![endif]-->
<!--[if IE 7 ]>    <html class="ie7"> <![endif]-->
<!--[if IE 8 ]>    <html class="ie8"> <![endif]-->
<!--[if IE 9 ]>    <html class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html class=""> <!--<![endif]-->

Then you can target IE versions with CSS rules:

.ie8 div.content_header_heading { 
}

See http://paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/.



回答2:

The best way I have come across is using a different CSS file for the Internet Explorer.

Then in your HTML you can exclude or include them using the typical conditional code blocks you find on the internet.

<!--[if IE 6]>
  CSS HERE
<![endif]-->

Only put in those lines of CSS that need to be different in that IE version.



回答3:

The best way to make sure every html element is interpreted (at all) by the browser is to use http://www.modernizr.com/

If you want to use header, footer or other new html5 elements modernizr will create them so that old browsers understand the elements.



回答4:

The simplest CSS hacks for different versions on IE are:

.color {color: #777;} /* for all browsers */
* html .color {color: #C39;} /* for IE6 */
*+html .color {color: #66F;} /* for IE7 (you can also use the long expresion " *:first-child+html ") */
.color {color: #0FC\0/;} /* for IE8, going last */

all of the above are hacks, but at least they use VALID CSS, except the hack for IE8 where i recommend using a conditional comment.