CSS 中用戶自定義字體 @font-face


@font-face 允許網頁中使用自定義的字體,這些自定義的字體被放置在服務器上,從而讓網頁擺脫對訪問者計算機上字體環境的依賴。

簡單的說,有了@font-face,只需將字體上傳到服務器端,無論訪問者計算機上是否安裝該字體,網頁都能夠正確的顯示。

@font-face 的語法規則如下,

@font-face {
  font-family: <fontName>;
  src: <source> [<format>];
  font-style: <style>;
  font-weight: <weight>;
}

font-family 屬性用來指定字體的名稱 (必須)。

source 屬性用來指定字體文件的存放路徑,可以是相對路徑或絕對路徑 (必須)。

formart 屬性用來指定字體的格式,支持 ttf,otf,wotf,eot,svg 等格式 (可選)。

font-style 屬性用來指定字體風格,比如斜體 oblique 或 italic,默認為 normal (可選)。

font-weight 屬性用來指定字體的粗細,比如 bold, 默認為 normal (可選)。

舉例如下:

我要讓網站使用統一字體 Cantarell,則先下載好該字體的四種版本:Regular,Bold,Oblique,BoldOblique,並將它們放在當前 css 文件的上一級目錄的 font 子目錄下 (即 ../font),然后在 css 文件中設置如下,

/* User Defined Font */
@font-face {
    font-family: 'myfont';
    src: url("../font/Cantarell-Regular-gloden.otf");
}
@font-face {
    font-family: 'myfont-bold';
    src: url("../font/Cantarell-Bold-gloden.otf");
    font-weight: bold; 
}
@font-face {
    font-family: 'myfont-oblique';
    src: url("../font/Cantarell-Oblique-golden.otf");
    font-style: oblique;
}
@font-face {
    font-family: 'myfont-bold-oblique';
    src: url("../font/Cantarell-BoldOblique-golden.otf");
    font-weight: bold;
    font-style: oblique;
}

使用時,可以對大部分元素設置一個公共字體,例如,

body, button, input, select, textarea {
    font-family: 'myfont';
}

然后對個別元素,設置其他字體,例如,

.header-box > ul.lf > li > a {
    /* font-weight: bolder; */
    font-family: 'myfont-bold';
}

對於默認有粗體的元素,例如 h1, h2, 等,需要明確指定使用自定義粗體,例如,

h1, h2, h3, h4 {
    font-family: 'myfont-bold';
}

 

===========================================================

本文大部分內容來自於網友博客:https://blog.csdn.net/ixygj197875/article/details/79323554

@font-face 的基本語法規則可參考:https://www.runoob.com/cssref/css3-pr-font-face-rule.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM