實現設計稿中英文不同字形設定

前言

有時會遇到設計稿中使用不同字體的中英文,如果要一直手動設定真是稍嫌麻煩,下方使用 「 @font-face 規則搭配 unicode-range 屬性 」的方式,在一般專案與 Vue Cli 專案讓系統去偵測中英文並配對對應的字型。

下方兩個範例使用兩種字體:

  1. 英文字體載入本地端資料夾。Monument Extended 字體載入點
  2. 中文字體使用 Google Font - Noto Sans Traditional Chinese

❒ Vue Cli + BS

GitHub 程式碼

GitHub Pages

範例

① 資料統整

  1. 新增資料夾,把英文字體檔丟入 fonts 資料夾內

    1. 開啟資料夾 src / assets ,新增 stylesheets / fonts 資料夾,把英文字體檔案丟 fonts 資料夾內。
  2. stylesheets 資料夾新增 all.scss 檔案,把所有樣式從這邊 @import

    1. 這邊 npm 載入 bootstrap,all.scss 使用 @import 引入。
  3. 於 App.vue @import all.scss 。

    1. 記得把 App.vue 下方 style 預設的 #app font-family 備註掉,不然會吃不到待會下方要設定的字型。
    1
    2
    3
    4
    <!-- @ 為路徑 src -->
    <style lang="scss">
    @import '@/assets/stylesheets/all';
    </style>

② 使用 @font-face 規則搭配 unicode-range 屬性

  • 使用 unicode-range ,它可分辨你是中文或英文。
    • 中文代碼 : unicode-range: U+4E00-9FFF;
    • 英文代碼 : unicode-range: U+00-024F;
  • 中文與英文 @font-face 中的 font-family 自訂一樣的名字 ( 例如 custom-font ),把 custom-font 加入 _variables.scss 中的 $font-family-sans-serif 的第一個。因為已經各自設定了 unicode-range ,所以系統會自己偵測中英文並配對對應字型。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// all.scss

// ----- 中文設定(google font)
@font-face {
font-family: custom-font;
src: local('Noto Sans TC'),
url(https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@400;700&display=swap)
format('embedded-opentype');
unicode-range: U+4E00-9FFF;
}
// ----- 英文設定(本地端文字檔)
@font-face {
font-family: custom-font;
src: local('PPMonumentExtended-Regular'),
url('@/assets/stylesheets/fonts/PPMonumentExtended-Regular.otf') format('opentype');
unicode-range: U+00-024F;
}

❒ 一般專案

GitHub 程式碼

GitHub Pages

① 資料整理

  1. 把載下本地端的英文字體放置專案資料夾內。
  2. 開啟 all.css 做字體設定。

② 使用 @font-face 規則搭配 unicode-range 屬性

  • 使用 unicode-range ,它可分辨你是中文或英文。
    • 中文代碼 : unicode-range: U+4E00-9FFF;
    • 英文代碼 : unicode-range: U+00-024F;
  • 中文與英文 @font-face 中的 font-family 自訂一樣的名字 ( 例如 custom-fonts ),把 custom-fonts 加入 body 中。因為已經各自設定了 unicode-range ,所以系統會自己偵測中英文並配對對應字型。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/* 中文設定(google font) */
@font-face {
font-family: custom-fonts;
src: local("Noto Sans TC"), url('https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@400;700&display=swap') format("embedded-opentype");
unicode-range: U+4E00-9FFF;
}
/* 英文設定(本地端文字檔) */
@font-face {
font-family: custom-fonts;
src: local("PPMonumentExtended-Regular"), url('./fonts/PPMonumentExtended-Regular.otf') format("opentype");
unicode-range: U+00-024F;
}
/* 中英文@font-face中的font-family自訂名加入body的 */
body {
font-family: custom-fonts;
}

參考資料