如何有条件地加载CSS

3
以下代码定义了如果浏览器不是IE,则执行:
<!--[if !IE]> -->
...
<!-- <![endif]-->

如果我想编辑上面的内容,以便...
IF IE but IE version is less than 9 .. SHOW THIS
ELSE IF IE version is greater than or equal to 9 OR Other Browser .. SHOW THIS

我该如何实现它呢?当我搜索时,我发现的都是如何判断是否为IE版本或根本不是IE的相关内容。

正如您所读的那样,条件注释仅适用于IE。通常我会先加载通用情况,然后使用条件注释加载IE版本特定的CSS。 - Jeremy Cook
这些被称为“条件注释”,并且在网络上有广泛的文档记录。 - CBroe
另外,IE 10及以上版本不支持条件注释。 - Jeremy Cook
相关内容:http://stackoverflow.com/questions/21613462/conditional-comments - Jeremy Cook
3个回答

4
您可以使用类似以下的内容:
<!--[if lt IE 7]>      <html class="ie6"> <![endif]-->
<!--[if IE 7]>         <html class="ie7"> <![endif]-->
<!--[if IE 8]>         <html class="ie8"> <![endif]-->
<!--[if gt IE 8]><!--> <html>         <!--<![endif]-->

然后通过以下方式定位您的选择器:

 .ie8 .your-selector

此处所述。

如果您想要一个开关,您也可以向html标签添加一个类,例如:

<!--[if gt IE 8]><!--> <html class ="i-am-so-happy-it-is-no-ancient-ie"><!--<![endif]-->

并像这样使用它:

.i-am-so-happy-it-is-no-ancient-ie .your-selector{...}
.ie6 .your-selector {...}

编辑 我忘记了IE 9.. 实际上,Paul Irish建议使用这个表单(稍微调整了一下,使得可以使用单个.ie .class 进行非ie切换 - 虽然你必须注意ie6不支持多个类,但你明白我的意思):

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

想要了解原因,请参见上方的链接


有趣,但让我感到不安。 - Jeremy Cook
我看到很多网站都使用这种方法。只需将常规的条件语句添加到其他浏览器中即可。正确吗? - SearchForKnowledge
@SearchForKnowledge 很不幸,我不记得为什么会这样(这有点复杂,在html5-boilerplate的github-repo中有一个线程),但是最后一个元素也会在普通浏览器中呈现。 - hugo der hungrige
哦,我相信它能工作。出于任何原因修改html都让我感到不舒服。我想这让我大脑中的编译器翻转了吧。 - Jeremy Cook
1
@JeremyCook 嗯,你不应该把放在doctype之前。文章中描述了IE6的一个问题,如果您使用最后一个示例的形式,则不应该发生这种情况。 - hugo der hungrige
显示剩余3条评论

2

如何使用条件注释来针对非IE浏览器。

<!--[if !IE]> -->
According to the conditional comment this is not IE 5-9
<!-- <![endif]-->

您可以做更高级的事情:http://www.impressivewebs.com/conditional-comments/

(意思是,您可以进行更高级的操作,请点击链接了解更多信息)

我接受这个答案...因为我想要针对!IE和其他浏览器来做一些事情。谢谢。 - SearchForKnowledge

2

在HTML页面中,您可以添加IE浏览器的CSS条件语句,但不能在CSS文件中添加。

目标为IE 8及更高版本

<!--[if gt IE 7]>
    <link rel="stylesheet" type="text/css" href="ie8-and-up.css" />
<![endif]-->

<!--[if gte IE 8]>
    <link rel="stylesheet" type="text/css" href="ie8-and-up.css" />
<![endif]-->

5
请记住,IE10+不支持条件注释(这是正确的做法)。 - Bojangles

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接