【CSS】載入網頁字體方法

font-face、google font、font-family、truetype

【CSS】載入網頁字體方法

font-face、google font、font-family、truetype


載入下載的字體

  1. 下載字體檔(.ttf),放在專案中的資料夾(fonts)

  1. 在css樣式檔中寫以下程式碼:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/*Regular*/
@font-face {
    font-family: 'MantouSans';
    src: url('../fonts/MantouSans-Regular.ttf') format('truetype');
    font-weight: normal;
    font-style: normal;
}

/*Bold*/
@font-face {
    font-family: 'MantouSans';
    src: url('../fonts/MantouSans-Bold.ttf') format('truetype');
    font-weight: bold;
    font-style: normal;
}

/*Italic*/
@font-face {
    font-family: 'MantouSans';
    src: url('../fonts/MantouSans-Italic.ttf') format('truetype');
    font-weight: normal;
    font-style: italic;
}

/*Bold Italic*/
@font-face {
    font-family: 'MantouSans';
    src: url('../fonts/MantouSans-BoldItalic.ttf') format('truetype');
    font-weight: bold;
    font-style: italic;
}

p{
    font-family: 'MantouSans', Arial, sans-serif;
}

檔案名稱:MantouSans-Regular,但只要寫MantouSans


font-family說明

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
body{
    font-family: sans-serif; /*無襯線體*/
    font-family: serif; /*襯線體*/
    font-family: monospace; /*等寬體*/
    font-family: cursive; /*手寫體*/
    font-family: fantasy; /*幻想體*/

    font-family: 'MantouSans', Arial, sans-serif;
    /*font-family: 第一種字體, 第二種字體, "第三種字體", "通用字";}*/
    /*通用字一定會有,通常放在最末端*/
}


src說明

1
2
3
4
5
6
7
@font-face {
    font-family: 'Helvetica';
    src: url('../fonts/Helvetica.woff') format("woff") /*附檔名.woff*/
         url('../fonts/Helvetica.ttf') format("truetype") /*附檔名.ttf*/
         url('../fonts/Helvetica.eot') format("embedded-opentype") /*附檔名.eot*/
         local("Helvetica") /*抓取使用者電腦的字體,但必須要精確的對應字體名稱,通常不建議使用*/
}


使google font引入方法

  1. Google Fonts網站

  1. 找到想要的字體後,點擊“Get font”,再點擊“Get embed code”

  1. link方法:直接寫在主要樣板中的head裡

1
2
3
4
5
<head>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">
</head>

  1. import方法:在custom.scss檔中引入

1
@import url('https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap');
css 

其他相關