Setting CSS for IE only?

2019-03-01 01:24发布

问题:

I have a simple div with a 2px thick border and absolute positioning thats hidden until its parent element is hovered over. Due to IEs box model, the position of said div is somewhat off in IE, but not any other browser. I don't want to add an entirely seperate style sheet for IE, I just want to modify the class itself if the browsing person is using IE.

So how does one modify or add a specific class for IE only?

回答1:

You need to use something called conditional comments. These only work in IE (other browsers will see them as comments) so they are a great way to target IE only.

Example - if you want something to be done in IE6 use the following:

<!--[if IE 6]>
Special instructions for IE 6 here
<![endif]--

To find out more, visit the official MSDN source regarding conditional comments.



回答2:

You can just add following conditional snippets at your html (or whatever) file. After that you can define new class attributes in your ie_stylesheet.css

  <!--[if IE]>
    <link type="text/css" rel="stylesheet" media="all" href="ie_stylesheet.css"/>
  <![endif]-->

I think there are enough explanations here.



回答3:

You can try and avoid the IE stylesheet by adding a CSS reset to the beginning of your stylesheet. Please take a look at the following: http://www.cssreset.com/scripts/html5-doctor-css-reset-stylesheet/

The reset should help making elements behave the same in all browsers.



回答4:

I've found this usage of conditional comments to be a pretty elegant way of tagging your <html> tag with classes that you can work with in your CSS and JS:

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

As a contrived example, if you want to target IE6 to make all links red, you would use specificity like this:

.lt-ie7 a {
  color: red;
}

No need for a separate style sheet.

Source: Conditional stylesheets vs CSS hacks? Answer: Neither!