浏览器CSS Hacks使用方法

时间:2014-01-29所属栏目: Html+css 来源: 热度:

在各个浏览器中周旋,是要有一定的功力的,这篇文章正是一个汇总,增强你的功力:

浏览器兼容可以说是前端开发所要面对的第一个挑战,目前我的电脑上已经安装了6种浏览器(基于IE内核的不算,如Maxthon等)。

CSS hacks利用浏览器的漏洞来隐藏特定浏览器的CSS规则。实现浏览器兼容主要有两种方式条件样式表和CSS Hacks(Selector Hacks、Attribute Hacks)。对此根据一些资料汇总了一些CSS Hacks方法。

1.条件样式表

像这样的代码你应该见过:

<link rel="stylesheet" type="text/css" href="css/style.css" />
  <!–[if IE]>

  <link rel="stylesheet" type="text/css"href="css/ie.css" />
< ![endif]–>

PS:yahoo的内部编码最佳做法并不建议使用有条件的样式表。它会增加额外的平均1或2个HTTP下载请求

2.选择器Hacks(Selector Hacks)

/* IE6 及以下 */
* html #uno { color: red }

/* IE7 */
*:first-child+html #dos { color: red }

/* IE7, FF, Saf, Opera */
html>body #tres { color: red }

/* IE8, FF, Saf, Opera (IE 6,7以外) */
html>/**/body #cuatro { color: red }

/* Opera 9.27 及以下, safari 2 */
html:first-child #cinco { color: red }

/* Safari 2-3 */
html[xmlns*=""] body:last-child #seis { color: red }

/* safari 3+, chrome 1+, opera9+, ff 3.5+ */
body:nth-of-type(1) #siete { color: red }

/* safari 3+, chrome 1+, opera9+, ff 3.5+ */
body:first-of-type #ocho { color: red }

/* saf3+, chrome1+ */
@media screen and (-webkit-min-device-pixel-ratio:0) {
#diez { color: red }
}

/* iPhone / mobile webkit */
@media screen and (max-device-width: 480px) {
#veintiseis { color: red }
}

/* Safari 2 – 3.1 */
html[xmlns*=""]:root #trece { color: red }

/* Safari 2 – 3.1, Opera 9.25 */
*|html[xmlns*=""] #catorce { color: red }

/* IE6-8以外 */
:root *> #quince { color: red }

/* IE7 */
*+html #dieciocho { color: red }

/* Firefox only. 1+ */
#veinticuatro, x:-moz-any-link { color: red }

/* Firefox 3.0+ */
#veinticinco, x:-moz-any-link, x:default { color: red }

PS:选择器Hacks方式比较多, 但只要代码写得够标准, 其实要 Hack 的地方不会很多的, 除了有时候IE捣乱,IE 以外的浏览器几乎都不会有问题。

3.属性hacks(Attribute Hacks)

    /* IE6 */
    #once { _color: blue }

    /* IE6, IE7 */
    #doce { *color: blue; /* 或 #color: blue */ }

    /* IE6以外 */
    #diecisiete { color/**/: blue }

    /* IE6, IE7, IE8 */
    #diecinueve { color: blue\9; }

    /* IE7, IE8 */
    #veinte { color/*\**/: blue\9; }

    /* 仅IE8 */
    #veinte { color: blue\0; }

PS:属性Hacks混写是我较多使用的一种方式,感觉写起来比较简单。CSS Hacks的使用大多情况下是为了兼顾一下爱捣乱的IE,使用Attribute Hacks基本上能解决对IE的兼容。

4.属性hacks混写

    /* !important优先 */
    #bgcolor {
    background:red !important; /* Firefox 等其他浏览器 */
    background:blue; /* IE6 */
    }

    #test {
    background-color: black; /* Firefox, Opera, IE8 */
    [;background-color: green;] /* Safari, Chrome */
    *background-color: blue; /* IE7 */
    _background-color: red; /* IE6 */
    }

PS:属性hacks混写要注意书写次序。

其实浏览器兼容不应该只对过去的浏览器兼容(向前兼容),更应该考虑为未来浏览器服务(向后兼容),所以开发时,要尽可能的符合标准,保持代码整洁是一件很重要的事情(参考《Keep CSS Simple》)不得已的时候才Hack一下。

标签:
评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)