前幾年已經開始流行icon font,很多項目為了節省網站空間,實現開發時靈活的圖標大小和顏色等樣式修改都已經采用icon font。css3里面自定義字符(@font-size)已經被各大瀏覽器支持,即便是古老的IE系列,可得到很好的支持。
基礎使用方法
兩種方法,一種是在標簽上用data-屬性,另外一種是使用class。
首先需要在css文件中引入相關的eot、woff、ttf、svg文件:
@font-face { font-family: 'ElegantIcons'; src:url('fonts/ElegantIcons.eot'); src:url('fonts/ElegantIcons.eot?#iefix') format('embedded-opentype'), url('fonts/ElegantIcons.woff') format('woff'), url('fonts/ElegantIcons.ttf') format('truetype'), url('fonts/ElegantIcons.svg#ElegantIcons') format('svg'); font-weight: normal; font-style: normal;
}
/* Use the following CSS code if you want to use data attributes for inserting your icons */ [data-icon]:before { font-family: 'ElegantIcons'; content: attr(data-icon); speak: none; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;
}
src: url('iconfont.eot'); /* 兼容IE9*/
src: url('iconfont.eot?#iefix') format('embedded-opentype'), /* 兼容IE6-IE8 */
url('iconfont.woff') format('woff'),/* 兼容chrome、firefox */
url('iconfont.ttf') format('truetype'),
/* 兼容chrome、firefox、opera、Safari, Android, iOS 4.2+*/
url('iconfont.svg#iconfont') format('svg'); /* 兼容iOS 4.1- */
插入一個圖標:
<div class="fs1" aria-hidden="true" data-icon="!" ></div>
上述的html標簽,插入即可看到效果。但是對於需要重新通過腳本獲取html標簽中的data-icon值,需要使用偽元素:before:
插入html標簽:
<i class="icon-group"></i>
同時需要配合樣式:
.icon-group{ font-family: 'ElegantIcons'; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; -webkit-font-smoothing: antialiased;
} i.icon-group:before{ content:'\e08b';
}
使用偽元素的好處就是編寫html標簽時候不需要記住繁瑣沒有規律的十六進制實體,而是記住icon-group這個class名即可,使得html更具語義化。
由於字體圖標會存在半個像素的鋸齒,在瀏覽器渲染的時候會直接顯示一個像素,導致在有背景下的圖標顯示感覺加粗;所以在應用字體圖標的時候需要對圖標樣式進行抗鋸齒處理,所以應該對CSS代碼設置屬性:
-webkit-font-smoothing: antialiased;
