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)
| Family | Mô tả | Ví dụ hệ thống |
|---|---|---|
system-ui | Font UI mặc định của OS | San Francisco (macOS/iOS), Segoe UI (Windows), Roboto (Android) |
ui-serif | Serif của OS | New York (macOS), Cambria (Windows) |
ui-sans-serif | Sans-serif của OS | San Francisco, Segoe UI, Roboto |
ui-monospace | Monospace của OS | SF Mono, Consolas, Roboto Mono |
ui-rounded | Rounded sans-serif của OS | SF Rounded (macOS/iOS) |
Best Practice
- Luôn kết thúc stack bằng generic family
- Ưu tiên
system-ui/-apple-system/BlinkMacSystemFontcho performance (zero download) - Dùng
font-display: swapvớ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