CSS 字體 (Font)

CSS 提供多個屬性來控制文字的字體樣式,包括字型、大小、粗細、斜體等。

font-family(字型)

font-family 用來指定文字要使用的字型。可以指定多個字型作為備用,瀏覽器會依序嘗試,使用第一個可用的字型。

body {
  font-family: "Microsoft JhengHei", "PingFang TC", Arial, sans-serif;
}

如果字型名稱包含空格,需要用引號包住。

通用字型系列

建議在字型清單最後加上通用字型系列 (generic font family) 作為最終備用:

名稱說明
serif襯線字體(有裝飾線),如 Times New Roman
sans-serif無襯線字體,如 Arial、Helvetica
monospace等寬字體,如 Courier New
cursive手寫風格字體
fantasy裝飾性字體
/* 正文用無襯線字體 */
body {
  font-family: "Noto Sans TC", sans-serif;
}

/* 程式碼用等寬字體 */
code {
  font-family: "Fira Code", Consolas, monospace;
}

font-size(字體大小)

font-size 設定文字的大小。

h1 {
  font-size: 32px;
}

p {
  font-size: 16px;
}

/* 使用相對單位 */
.small {
  font-size: 0.875rem;  /* 14px (假設根元素是 16px) */
}

.large {
  font-size: 1.25rem;   /* 20px */
}

常見的字體大小單位:

  • px:固定大小
  • rem:相對於根元素的字體大小(推薦)
  • em:相對於父元素的字體大小
  • %:相對於父元素的百分比

font-weight(字體粗細)

font-weight 設定文字的粗細程度。

.normal {
  font-weight: normal;   /* 等於 400 */
}

.bold {
  font-weight: bold;     /* 等於 700 */
}

.light {
  font-weight: 300;
}

.heavy {
  font-weight: 900;
}

數值範圍從 100 到 900,通常以 100 為間隔:

數值關鍵字
100thin
200extra-light
300light
400normal
500medium
600semi-bold
700bold
800extra-bold
900black
不是所有字型都支援所有粗細等級,如果指定的粗細不存在,瀏覽器會使用最接近的粗細。

font-style(字體樣式)

font-style 設定文字是否為斜體。

.normal {
  font-style: normal;
}

.italic {
  font-style: italic;    /* 斜體 */
}

.oblique {
  font-style: oblique;   /* 傾斜(模擬斜體) */
}
  • italic:使用字型本身的斜體版本
  • oblique:將正常字型傾斜顯示

font-variant(小型大寫)

font-variant 可以將小寫字母顯示為縮小的大寫字母。

.small-caps {
  font-variant: small-caps;
}

font(縮寫屬性)

font 是一個縮寫屬性,可以一次設定多個字體相關屬性。

/* font: font-style font-variant font-weight font-size/line-height font-family; */

p {
  font: italic bold 16px/1.5 Arial, sans-serif;
}

/* 等同於 */
p {
  font-style: italic;
  font-weight: bold;
  font-size: 16px;
  line-height: 1.5;
  font-family: Arial, sans-serif;
}

使用縮寫時,font-sizefont-family 是必須的,其他可以省略。

網頁字型 (Web Fonts)

除了系統內建字型,還可以使用網頁字型讓所有使用者看到相同的字型。

Google Fonts

<!-- 在 HTML 中引入 -->
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+TC&display=swap" rel="stylesheet">
body {
  font-family: 'Noto Sans TC', sans-serif;
}

@font-face

自行載入字型檔案:

@font-face {
  font-family: 'MyFont';
  src: url('/fonts/myfont.woff2') format('woff2'),
       url('/fonts/myfont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

body {
  font-family: 'MyFont', sans-serif;
}