Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Kết hợp font (Font Stacks) trong CSS3

Giới thiệu

CSS3 cho phép khai báo font stack (danh sách font dự phòng) qua font-family. Trình duyệt sẽ thử lần lượt: nếu font đầu không có → thử font tiếp theo → cuối cùng dùng font hệ thống generic family.

Cú pháp

font-family: "Font Chính", "Font Dự Phòng 1", "Font Dự Phòng 2", generic-family;
  • Tên font có khoảng trắng → bọc trong ngoặc kép/đơn
  • Generic family: serif, sans-serif, monospace, cursive, fantasy, system-ui, ui-serif, ui-sans-serif, ui-monospace, ui-rounded

Ví dụ: Sans-Serif Font Stack phổ biến

<style>
  /* System UI font stack - hiện đại, hiệu năng tốt, không tải font ngoài */
  .system-sans {
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  }
  
  /* Classic web-safe stack */
  .classic-sans {
    font-family: Arial, Helvetica, sans-serif;
  }
  
  /* Modern geometric sans */
  .geometric-sans {
    font-family: 'Inter', 'Roboto', 'Helvetica Neue', Arial, sans-serif;
  }
  
  /* Serif cho nội dung dài (bài viết, blog) */
  .content-serif {
    font-family: Georgia, 'Times New Roman', serif;
  }
  
  /* Monospace cho code */
  .code-mono {
    font-family: 'Fira Code', 'JetBrains Mono', 'SF Mono', Menlo, Consolas, monospace;
  }
</style>

@font-face — Tự host font tùy chỉnh

@font-face {
  font-family: 'MyCustomFont';
  src: url('/fonts/myfont.woff2') format('woff2'),
       url('/fonts/myfont.woff') format('woff');
  font-weight: 400;
  font-style: normal;
  font-display: swap; /* Quan trọng: tránh FOIT/FOUT */
}

/* Sử dụng */
body { font-family: 'MyCustomFont', system-ui, sans-serif; }

Generic Font Families (CSS Fonts 4)

FamilyMô tảVí dụ hệ thống
system-uiFont UI mặc định của OSSan Francisco (macOS/iOS), Segoe UI (Windows), Roboto (Android)
ui-serifSerif của OSNew York (macOS), Cambria (Windows)
ui-sans-serifSans-serif của OSSan Francisco, Segoe UI, Roboto
ui-monospaceMonospace của OSSF Mono, Consolas, Roboto Mono
ui-roundedRounded sans-serif của OSSF Rounded (macOS/iOS)

Best Practice

  • Luôn kết thúc stack bằng generic family
  • Ưu tiên system-ui / -apple-system / BlinkMacSystemFont cho performance (zero download)
  • Dùng font-display: swap với @font-face
  • Preload font quan trọng: <link rel="preload" as="font" href="font.woff2" crossorigin>
  • Variable font: một file chứa nhiều weight/style — giảm request