Is there any way to do “if IE” inside of a CSS file?

这一生的挚爱 提交于 2020-01-23 05:22:11

问题


I know you can put conditional statements to load different CSS files if you are in Internet Explorer, but can you do this inside of a CSS file?

I have a situation where I want the right margin to be 20 if it's Internet Explorer but 10 if it's any other browser.


回答1:


The easiest way to handle this is with conditions in your HTML that put a div with a specific id around the rest of the page.

<!--[If IE 8]>
<div id="IE8">
<![endif]-->
  .
  .
  .
<!--[If IE 8]>
</div>
<![endif]-->

Then, your CSS can do this:

#IE8 div.whatever { ... }

This sort of makes all those CSS hacks unnecessary.




回答2:


There is no official conditional comment syntax for CSS. There are only conditional HTML and JavaScript comments, so get creative with those (John Fisher shows one way).

You could emulate conditional CSS by using the very well-known CSS hacks, but I'd rather not. They could break or otherwise work unexpectedly at any arbitrary version of IE, because hacks are meant to exploit bugs in IE's handling of CSS.




回答3:


There are hacks like this one where using rules that IE fails to interpret means that IE stops processing a rule leaving it safe to use for other browsers.

Like this:

div.iehack { 
  margin-right:20px; 
  voice-family: "\"}\""; 
  voice-family:inherit;
  margin-right:10px; 
} 



回答4:


You will make a mess of your css files doing these kind of hacks. Better make a separate file for IE. Set the margin to 10 in your general css file, and set it to 20 in your IE specific file, which should be (conditionally) loaded after your general css file. You know how to do this and there's hardly a reason to do it any other way.



来源:https://stackoverflow.com/questions/4422510/is-there-any-way-to-do-if-ie-inside-of-a-css-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!