1.簡介
@font-face用於自定義字體樣式,從服務器端取得字體樣式,使瀏覽器可以顯示客戶端並不存在的樣式效果,給用戶帶來更好的展示體驗。
@font-face並不是CSS3的新特性,早在98年就被寫入CSS2的規范當中,目前在IE6都可支持。
2.語法
@font-face { font-family: <FontName>; //自定義的字體名稱 src: <source> [<format>][,<source> [<format>]]*; //字體文件路徑 [font-weight: <weight>]; //是否加粗 [font-style: <style>]; //是否斜體 }
由於各個瀏覽器對字體文件支持格式不同,所以我們一般引用多個格式的字體文件(
eot\woff\ttf\svg),font-weight用於設置字體粗細,font-style用於設置是否是斜體。
Tip:一般我們容易得到的字體文件是ttf格式的,可以通過
http://www.fontsquirrel.com/tools/webfont-generator 將ttf轉換為其他幾種字體。
3.實踐效果:
Demo下載(第二種效果字體文件略大)
4.相關資料
https://icomoon.io/ 利用圖標制作圖片
http://www.dafont.com/ 字體庫
http://www.w3cplus.com/content/css3-font-face/ font-face詳解(非常詳細,推薦)
5.Bootstrap中的@font-face
Bootstrap2.x中的glyphicon組件是利用CSS Spirit實現小圖標的展示效果,到了3.x改用@font-face實現,源碼如下:
@font-face { //引入字體文件
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff2') format('woff2'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
}
.glyphicon { //基礎樣式
position: relative;
top: 1px;
display: inline-block;
font-family: 'Glyphicons Halflings';
font-style: normal;
font-weight: normal;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
//小圖標內容設置
.glyphicon-cloud:before {
content: "\2601";
}
.glyphicon-envelope:before {
content: "\2709";
}
……共計200+圖標樣式(具體可參考 http://v3.bootcss.com/components/)
可以注意到,這里都是用content:""設置的,應用時給相應元素(一般為span或ul)加上
“glyphicon glyphicon -***”類即可。多說一句,如果不利用before偽元素的特性,如何在普通文本上顯示小圖標呢?這里content內的字符默認是保存在Unicode Private Use Area(即用戶自定義字符區域)中的,如果要在HTML中使用則需加
&#x,這個原理是將其轉化為html實體。以下兩個span的顯示效果是相同的。
<span class="
glyphicon glyphicon-envelope"></span>
<span class="
glyphicon">
✉</span>
OK,That's all,歡迎吐槽。
