前幾年已經開始流行icon font,不少項目爲了節省網站空間,實現開發時靈活的圖標大小和顏色等樣式修改都已經採用icon font。css3裏面自定義字符(@font-size)已經被各大瀏覽器支持,即使是古老的IE系列,可獲得很好的支持。css
基礎使用方法html
兩種方法,一種是在標籤上用data-屬性,另一種是使用class。css3
首先須要在css文件中引入相關的eot、woff、ttf、svg文件:web
@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*/chrome
src: url('iconfont.eot?#iefix') format('embedded-opentype'), /* 兼容IE6-IE8 */瀏覽器
url('iconfont.woff') format('woff'),/* 兼容chrome、firefox */svg
url('iconfont.ttf') format('truetype'), 字體
/* 兼容chrome、firefox、opera、Safari, Android, iOS 4.2+*/網站
url('iconfont.svg#iconfont') format('svg'); /* 兼容iOS 4.1- */url
插入一個圖標:
<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;