參考
1.史上最全的CSS hack方式一覽
2.前端的瑞士軍刀:Modernizr.js
3.CSS hack-wikipedia
4.CSS hack-baidu
5.關于CSS Reset 那些事(一)之 歷史演變與Normalize.css
一、什么是 CSS hack?
瀏覽器因類型、版本的不同,對CSS的支持程度、解析不一致。這導致了同樣的CSS在不同瀏覽器下的頁面效果不同。為了獲得統一的頁面效果,針對不同的瀏覽器或不同版本編寫特定的CSS樣式的過程,叫做CSS hack。
二、瀏覽器兼容的思路
- 是否需要
- 產品角度:產品受眾及其使用瀏覽器比例,效果優先還是功能優先;
- 成本角度:有無必要。
- 兼容程度
- 最低兼容瀏覽器類型或版本,需要實現怎樣的效果。
- 怎樣實現
- 合適的技術框架或庫;
- 明確要漸進增強還是優雅降級;
- 選擇合適的兼容工具;(html5shiv.js、respond.js、css reset、normalize.css、Modernizr)
- CSS hack(條件注釋等)、js能力檢測。
三、列舉5種以上瀏覽器兼容的寫法
- 條件注釋(IE 9及以下)
- IE 6時,
<p>You are using Internet Explorer 6.</p>
有效; - 除IE 9及以下版本之外的其他瀏覽器有效;
- IE 8時,載入ie8only.css。
- IE 6時,
<!--[if IE 6]>
<p>You are using Internet Explorer 6.</p>
<![endif]-->
<!--[if !IE]><!-->
<script>alert(1);</script>
<!--<![endif]-->
<!--[if IE 8]>
<link href="ie8only.css" rel="stylesheet">
<![endif]-->
- 屬性前綴法
.box{
color: red;
color: yellow\9; /*ie 6~10*/
*color: pink; /*ie 6~7*/
-color: blue; /*ie 6*/
}
- 選擇器前綴法
/*for Chrome/Safari*/
@media screen and (-webkit-min-device-pixel-ratio:0){
.hacktest {
background-color:gray;
}
}
- 利用js根據瀏覽器UA添加屬性值
//js在html標簽中嵌入用戶瀏覽器的UA
var htmlObj = document.documentElement;
htmlObj.setAttribute('data-useragent',navigator.userAgent);
htmlObj.setAttribute('data-platform', navigator.platform );
/*將特定CSS匹配到所檢測到的用戶瀏覽器*/
html[data-useragent*='MSIE 10.0'] #id {
color: #F00;
}
- 利用工具如:Modernizr
應用modernizr.js后,運行時會生成當前瀏覽器支持和不支持的特性
<html class=" js no-flexbox canvas canvastext no-webgl no-touch geolocation
postmessage no-websqldatabase no-indexeddb hashchange no-history
draganddrop no-websockets rgba hsla multiplebgs backgroundsize
no-borderimage borderradius boxshadow no-textshadow opacity
no-cssanimations no-csscolumns no-cssgradients no-cssreflections
csstransforms no-csstransforms3d no-csstransitions fontface
generatedcontent video audio localstorage sessionstorage
no-webworkers no-applicationcache svg inlinesvg smil svgclippaths">
然后我們可以針對支持與不支持分別編寫樣式,如box-shadow:
.boxshadow #MyContainer {
border: none;
-webkit-box-shadow: #666 1px 1px 1px;
-moz-box-shadow: #666 1px 1px 1px;
}
.no-boxshadow #MyContainer {
border: 2px solid black;
}
四、以下工具/名詞是做什么的
條件注釋
條件注釋只在IE中生效,是IE瀏覽器私有的代碼,是一個類似if判斷的語法注釋塊。IE Hack
就是針對低版本IE瀏覽器編寫的只被其識別的樣式等,以此保持頁面效果與其他瀏覽器的一致性。js 能力檢測
利用js來檢測當前瀏覽器是否支持一些特性或方法。html5shiv.js
在IE9及以下的瀏覽器中生成可用的html5中的新標簽。respond.js
是一個快速、輕量的 polyfill,用于為 IE6-8 以及其它不支持 CSS3 Media Queries 的瀏覽器提供媒體查詢的 min-width 和 max-width 特性,實現響應式網頁設計。css reset
通過重新定義標簽樣式,將瀏覽器默認樣式覆蓋。normalize.css
保留有用的瀏覽器默認樣式,為html元素的默認樣式提供了跨瀏覽器的高度一致性;同時也修復了瀏覽器的一些bug。Modernizr
檢測瀏覽器是否支持CSS或js的特性。如果支持,那么開發人員就可以充分利用這些特性做一些工作,反之,開發人員也好提供一個平穩退化的替代方案。postCSS
postCSS是一個js插件轉換樣式表的工具。這些插件能夠檢驗你的CSS、支持變量和混合,轉化CSS3的新特性語法、行內圖片等。