常用 CSS Hack 再整理
9:07 am in E-learning by Ka-Yue Yeung 楊家儒
瀏覽器越來越多,舊的未去,新的又來,CSS hacks 亦需定時整理。
CSS Hack
IE hacks
雖然 IE 對 CSS 的支援不堪入目,可是卻有方便的屬性 hacks!把下列 hacks 記下來即可輕鬆應付各版本的 IE!
.selector {
padding: 10px;
padding: 9px\9; /* all ie */
padding: 8px\0; /* ie8-9 */
*padding: 5px; /* ie6-7 */
+padding: 7px; /* ie7 */
_padding: 6px; /* ie6 */
}
Firefox hacks
/* Target Firefox 2 and older */
body:empty .selector {
color: red;
}
/* Target FireFox 3 */
html>/**/body .selector, x:-moz-any-link, x:default {
color: red;
}
來源:CSS Hacks for Different Versions of Firefox
WebKit hacks
針對 Chrome 和 Safari 的 hack
/* webkit */
@media screen and (-webkit-min-device-pixel-ratio:0) {
.selector { padding:11px; }
}
Javascript
Javascript 的解決方案都不外乎先在 Javascript 做版本檢測,之後在 html 或 body 上加上相應的 class。這樣做的好處是不用在 css 裡加入各種奇形怪狀的 hack,也不用處理日後 css hack 的相容性問題。缺點是它要依賴 Javascript,反應也可能比較慢…
jQuery
這一段 code 可以自動在 body tag 上加入 IE6 class
if( jQuery.browser.msie && parseInt(jQuery.browser.version) === 6 ) {
$("body").addClass("ie6");
}
請各位自行舉一反三,詳情請閱 http://api.jquery.com/jQuery.browser/
Modernizr
如果你常常在網站上用到 CSS3 的話,又同時要支援舊瀏覽器,Modernizr 可能對你有用。Modernizr 會就瀏覽器支援的 css3 屬性在 <html> 加入相應的 class。
例如我想用多背景圖的話:
.multiplebgs div p {
/* properties for browsers that support multiple backgrounds */
}
.no-multiplebgs div p {
/* optional fallback properties for browsers that don't */
}
更多例子請見 http://www.modernizr.com/docs/。雖然我覺得這樣做有點多餘啦,如果要完美支援舊時代瀏覽器的話不如直接放棄 CSS3 好了。
HTML Conditional Comments
最近我還學到了這種不用 Javascript 而又可以在 <body> 加 class 的寫法:
<!--[if IE6]--><body class="ie6"><![endif]--> <!--[if IE7]--><body class="ie7"><![endif]--> <!--[if IE8]--><body class="ie8"><![endif]--> <!--[if IE9]--><body class="ie9"><![endif]--> <!--[if !IE]--><body class="non-ie"><![endif]-->
很好很強大,長得醜一點就是了。



rizrizrizriz@hotmail.com
Fleet Summaries




