温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

什么是CSS hack

发布时间:2021-01-29 13:55:50 来源:亿速云 阅读:220 作者:小新 栏目:web开发

小编给大家分享一下什么是CSS hack,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

什么是CSS hack

CSS hack由于不同的浏览器,比如IE6,IE7,Firefox等,对CSS的解析认识不一样,因此会导致生成的页面效果不一样,得不到我们所需要的页面效果。 这个时候我们就需要针对不同的浏览器去写不同的CSS,让它能够同时兼容不同的浏览器,能在不同的浏览器中也能得到我们想要的页面效果。

CSS hack分类

hack主要分为CSS选择器hack、CSS属性hack、IE条件注释hack。

CSS选择器hack:比如 IE6能识别*html .class{},IE7能识别*+html .class{}或者*:first-child+html .class{}等。

CSS属性hack:比如 IE6能识别下划线"_"和星号" * ",IE7能识别星号" * ",但不能识别下划线"_",而firefox两个都不能认识等。

IE条件注释hack:

针对所有IE:<!--[if IE]><!--您的代码--><![endif]-->

针对IE6及以下版本:<!--[if lt IE 7]><!--您的代码--><![endif]-->

这类Hack不仅对CSS生效,对写在判断语句里面的所有代码都会生效。

书写顺序,一般是将识别能力强的浏览器的CSS写在前面。

用法

比如要分辨IE6和firefox两种浏览器,可以这样写:

div{
background:green; /* for firefox */
*background:red; /* for IE6 */ (both IE6 && IE7)
}

可以看到在IE6中看到是红色的,在firefox中看到是绿色的。

在firefox中,它是识别不了后面的那个带星号的东西是什么的,于是将它过滤掉,解析得到的结果是:div{background:green},于是理所当然这个div的背景是绿色的。

在IE6中,它两个background都能识别出来,它解析得到的结果是:div{background:green;background:red;},于是根据优先级别,处在后面的red的优先级高,于是当然这个div的背景颜色就是红色的了。

浏览器识别

<!DOCTYPE html>  
<html>  
<head>  
    <title>Css Hack</title>  
    <style>  
    #test   
    {   
        width:300px;   
        height:300px;             
        background-color:blue;      /*firefox*/
        background-color:red\9;      /*all ie*/
        background-color:yellow\0;    /*ie8*/
        +background-color:pink;        /*ie7*/
        _background-color:orange;       /*ie6*/
    }  
    :root #test { background-color:purple\9; }  /*ie9*/
    @media all and (min-width:0px){ #test {background-color:black\0;} }  /*opera*/
    @media screen and (-webkit-min-device-pixel-ratio:0){ #test {background-color:gray;} }  /*chrome and safari*/
    </style>  
</head>  
<body>  
    <div id="test">test</div>  
</body>  
</html>

上面这段代码大家可以直接copy出来,保存成html在各浏览器试试。分析:

(1)background-color:blue; 各个浏览器都认识,这里给firefox用;

(2)background-color:red\9; \9所有的ie浏览器可识别;

(3)background-color:yellow\0; \0 是留给ie8的,但笔者测试,发现最新版opera也认识,汗。。。不过且慢,后面自有hack写了给opera认的,所以,\0我们就认为是给ie8留的;

(4)+background-color:pink; + ie7定了;

(5)_background-color:orange; _专门留给神奇的ie6;

(6):root #test { background-color:purple\9; } :root是给ie9的,网上流传了个版本是 :root #test { background-color:purple\0;},新版opera也认识,所以经笔者反复验证最终ie9特有的为:root 选择符 {属性\9;}

(7)@media all and (min-width:0px){ #test {background-color:black\0;} } 这个是老是跟ie抢着认\0的神奇的opera,必须加个\0,不然firefox,chrome,safari也都认识。。。

(8)@media screen and (-webkit-min-device-pixel-ratio:0){ #test {background-color:gray;} }最后这个是浏览器新贵chrome和safari的。

看完了这篇文章,相信你对“什么是CSS hack”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI