简单介绍CSS hack的使用

Naomi ·
更新时间:2024-09-20
· 755 次阅读

css hack 是个很有争议的东西,一开始我也很讨厌,因为我觉得可以饶过 css hack,通过另外的方法解决问题。但是,随着工作中的不断实践,改变了我的观点,css hack 虽然不能通过 w3c 标准认证,但适当是使用很有可能会使你的 HTML 结构更紧凑、有效的减少无语义标签或带来其他好处。

1.IE条件注释法
该方法安全性好,但是不利于开发维护。比如涉及到针对不同版本IE的css。

<!--[if IE]><![endif]-->         只在IE下有效
<!--[if IE 6]><![endif]-->      只在IE6有效
<!--[if gt IE 6]><![endif]-->  只在IE6以上版本有效

注意:结合lte、lt、gte、gt、!关键字使用。

2.选择符前缀法

“*html” 前缀只对IE6生效  "*+html"前缀只对IE7生效

CSS Code复制内容到剪贴板 .test{width:80px;}           /*IE 6 7 8*/   *html .test{width:70px;}  /*IE6*/   *+html .test{width:60px;}/*IE7*/  

缺点:不能保证IE9,10不识别*html,*+html,有向后兼容风险。

3.样式属性前缀法:

如“_”只在IE6下生效,“*”在IE6和IE7下生效。同样有向后兼容隐患。
.test{width:80px;*width:70px;_width:60px;}

可用于内联样式

CSS Code复制内容到剪贴板 :<div style="width:80px;*width:70px;_width:60px;"></div>   

由于IE条件注释法不利于开发维护,实际中常用的hack方法常常是后两者。

小例子

html 代码

XML/HTML Code复制内容到剪贴板 <body>    <p>您的浏览器是</p>   </body>  

css hack 代码

CSS Code复制内容到剪贴板 p { margin:0; padding:0 55px 0 0; height:30xp; line-height:30px; font-size:14px;}    p { background:url(llq.gif) 90px -170px no-repeat;} /* all */   p,x:-moz-any-link { background:url(llq.gif) 90px -80px no-repeat;} /* for ff */   p,x:-moz-any-link,x:default { background:url(llq.gif) 90px -140px no-repeat;} /* for ff2+ */   p {[;background:url(llq.gif) 90px -260px no-repeat;]}  /* for sa/ch */   p { background:url(llq.gif) 90px -50px no-repeat\9;}  /* for ie */   *+html p { background:url(llq.gif) 90px -20px no-repeat;} /* only for ie7 */   p { _background:url(llq.gif) 90px 10px no-repeat;} /* only for ie6 */  


查看Demo

因为没有找到 op10 的 css hack,所以标准的写法是给 op10 的,然后针对其他浏览器写 css hack。

另外,在修复过程中,我发现了网上流传的一个 css hack 有问题,这个 css hack 也许有很多人在用,就是[属性:值\0],有的人说这是 ie8 专用的,但我在测试过程中发现这个 css hack 除了 ie8 识别外,ff3 和 op10 也能识别(ff2 和 ff3.5 不能识别)。



hack CSS

需要 登录 后方可回复, 如果你还没有账号请 注册新账号