什麼是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) |