前端学习 -- Html&Css -- 条件Hack 和属性Hack

条件Hack

语法:

<!--[if <keywords>? IE <version>?]>
HTML代码块
<![endif]-->

<keywords>

if条件共包含6种选择方式:是否、大于、大于或等于、小于、小于或等于、非指定版本

是否:
指定是否IE或IE某个版本。关键字:空
大于:
选择大于指定版本的IE版本。关键字:gt(greater than)
大于或等于:
选择大于或等于指定版本的IE版本。关键字:gte(greater than or equal)
小于:
选择小于指定版本的IE版本。关键字:lt(less than)
小于或等于:
选择小于或等于指定版本的IE版本。关键字:lte(less than or equal)
非指定版本:
选择除指定版本外的所有IE版本。关键字:!

<version>

目前的常用IE版本为6.0及以上,推荐酌情忽略低版本,把精力花在为使用高级浏览器的用户提供更好的体验上

用于选择IE浏览器及IE的不同版本

  • if条件Hack是HTML级别的(包含但不仅是CSS的Hack,可以选择任何HTML代码块)
<!--[if IE]>
<p>你在非IE中将看不到我的身影</p>
<![endif]-->

示例demo:

<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8" />
<title>if条件Hack_CSS参考手册_web前端开发参考手册系列</title>
<style>
h1{margin:10px 0;font-size:16px;}
span{display:none;}
.not-ie{display:inline;}
</style>
<!--[if IE]>
<style>
.ie{display:inline;}
.not-ie{display:none;}
</style>
<![endif]-->

<!--[if IE 5]>
<style>
.ie5{display:inline;}
</style>
<![endif]-->

<!--[if IE 6]>
<style>
.ie6{display:inline;}
</style>
<![endif]-->

<!--[if IE 7]>
<style>
.ie7{display:inline;}
</style>
<![endif]-->

<!--[if IE 8]>
<style>
.ie8{display:inline;}
</style>
<![endif]-->

<!--[if IE 9]>
<style>
.ie9{display:inline;}
</style>
<![endif]-->
</head>
<body>
<div>
    您正在使用
    <span class="not-ie">非IE</span>
    <span class="ie">IE</span>
    <span class="ie5">5</span>
    <span class="ie6">6</span>
    <span class="ie7">7</span>
    <span class="ie8">8</span>
    <span class="ie9">9</span>
    浏览器
</div>
</body>
</html>
            

语法:

selector{<hack>?property:value<hack>?;}

_:

选择IE6及以下。连接线(中划线)(-)亦可使用,为了避免与某些带中划线的属性混淆,所以使用下划线(_)更为合适。
*:
选择IE7及以下。诸如:(+)与(#)之类的均可使用,不过业界对(*)的认知度更高
\9:
选择IE6+
\0:
选择IE8+和Opera
[;property:value;];:
选择webkit核心浏览器(Chrome,Safari)。IE7及以下也能识别。中括号内外的3个分号必须保留,第一个分号前可以是任意规则或任意多个规则
[;color:#f00;]; 与 [color:#f00;color:#f00;]; 与 [margin:0;padding:0;color:#f00;]; 是等价的。生效的始终是中括号内的最后一条规则,所以通常选用第一种写法最为简洁。

选择不同的浏览器及版本

  • 尽可能减少对CSS Hack的使用。Hack有风险,使用需谨慎
  • 通常如未作特别说明,本文档所有的代码和示例的默认运行环境都为标准模式。
  • 一些CSS Hack由于浏览器存在交叉认识,所以需要通过层层覆盖的方式来实现对不同浏览器进行Hack的。

示例:

<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8" />
<title></title>
<style>
h1{margin:10px 0;font-size:16px;}
.test{
    color:#c30;          /* For Firefox */
    [;color:#ddd;];      /* For webkit(Chrome and Safari) */
    color:#090\0;        /* For Opera */
    color:#00f\9;        /* For IE8+ */
    *color:#f00;         /* For IE7 */
    _color:#ff0;         /* For IE6 */
}
</style>
</head>
<body>
<div class="test">在不同浏览器下看看我的颜色吧</div>
</body>
</html>