什么是CSS hackhtml
CSS hack因为不一样的浏览器,好比IE6,IE7,Firefox等,对CSS的解析认识不同,所以会致使生成的页面效果不同,得不到咱们所须要的页面效果。 这个时候咱们就须要针对不一样的浏览器去写不一样的CSS,让它可以同时兼容不一样的浏览器,能在不一样的浏览器中也能获得咱们想要的页面效果。web
CSS hack分类chrome
hack主要分为CSS选择器hack、CSS属性hack、IE条件注释hack。浏览器
CSS选择器hack:好比 IE6能识别*html .class{},IE7能识别*+html .class{}或者*:first-child+html .class{}等。测试
CSS属性hack:好比 IE6能识别下划线"_"和星号" * ",IE7能识别星号" * ",但不能识别下划线"_",而firefox两个都不能认识等。url
IE条件注释hack:spa
针对全部IE:<!--[if IE]><!--您的代码--><![endif]-->firefox
针对IE6及如下版本:<!--[if lt IE 7]><!--您的代码--><![endif]-->code
这类Hack不只对CSS生效,对写在判断语句里面的全部代码都会生效。htm
书写顺序,通常是将识别能力强的浏览器的CSS写在前面。
用法
好比要分辨IE6和firefox两种浏览器,能够这样写:
div{ background:green; /* for firefox */ *background:red; /* for IE6 */ (both IE6 && IE7) }
能够看到在IE6中看到是红色的,在firefox中看到是绿色的。
<!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 |
---|---|
IE6 | _background-color:#38DB24; |
IE67 | *background-color:#38DB24 ; |
IE67 | +background-color:#38DB24 ; |
IE67 | #background-color:#38DB24; |
IE67 | background-color:#38DB24 !ie; |
IE678910 | background-color:#38DB24\9; |
IE78910&Firefox&Opera&Chrome&Safari | html>body .ie78910-all-hack |
IE8910&Firefox&Opera&Chrome&Safari | html>/**/body .ie8910-all-hack |
IE8910&Opera | background-color:#38DB24\0; |
IE910 | :root .ie910-hack |
IE910 | background-color:#38DB24\9\0; |
IE910&Firefox&Opera&Chrome&Safari | body:nth-of-type(1) .ie910-all-hack |
IE910&Firefox&Opera&Chrome&Safari | @media all and (min-width: 0px) |
IE910&Firefox&Opera&Chrome&Safari | @media all and (min-width: 0px) |
IE910&Firefox&Opera&Chrome&Safari | :root *> .ie910-all-4-hack |
IE10 | @media screen and (-ms-high-contrast: active), |
Firefox | @-moz-document url-prefix() |
Chrome&Safari | @media screen and (-webkit-min-device-pixel-ratio:0) |