Google Fonts เป็นบริการฟอนต์ฟรีจาก Google ที่นำมาใช้งานง่าย เพียงเพิ่ม Link Tag หรือ @import ใน CSS แล้วใช้ font-family ตามปกติ ตัวอย่างนี้ใช้ฟอนต์ "Permanent Marker" สไตล์มือเขียน
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Permanent+Marker&display=swap" rel="stylesheet"/>
<style>
body {
font-family: "Permanent Marker", cursive;
font-size: 22px;
}
</style>
</head>
<body>
<h1>Google fonts example</h1>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Debitis non a quos repudiandae doloribus cumque! Ex rem rerum aut maiores.</p>
<h2>1 2 3 4 5 6 7 8 9 10</h2>
</body>
</html>
วิธีการใช้งาน 2 แบบ
1. Link Tag (แนะนำ - เร็วกว่า)
<link href="https://fonts.googleapis.com/css2?family=Permanent+Marker&display=swap" rel="stylesheet">
- วางใน
<head> - Browser โหลดขนานกับ HTML ได้ (Preload)
- รองรับ
preconnectเพื่อลด Latency
2. @import ใน CSS
@import url('https://fonts.googleapis.com/css2?family=Permanent+Marker&display=swap');
- วางบนสุดของ CSS File
- โหลดแบบ Sequential (ช้ากว่า Link Tag)
- ไม่แนะนำสำหรับ Production
การเพิ่มประสิทธิภาพ (Performance Optimization)
- Preconnect:
<link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> - Font Display: ใช้
&display=swapป้องกัน FOIT (Flash of Invisible Text) - Subset: โหลดเฉพาะ Character ที่ต้องใช้
&text=HelloWorld - Variable Fonts: ใช้ Variable Font (หนึ่งไฟล์หลาย Weight) ลดขนาดไฟล์
ฟอนต์ยอดนิยมจาก Google Fonts
| Font | Category | เหมาะสำหรับ |
|---|---|---|
| Inter | Sans-serif | UI, Body text, Modern web |
| Roboto | Sans-serif | Material Design, General |
| Open Sans | Sans-serif | Readable, Multi-language |
| Poppins | Sans-serif | Headings, Modern |
| Merriweather | Serif | Article, Blog, Reading |
| Playfair Display | Serif | Elegant Headings |
| JetBrains Mono | Monospace | Code, Technical |
การใช้งานหลาย Fonts พร้อมกัน
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700&family=Merriweather:wght@400;700&display=swap" rel="stylesheet">
Self-hosting Google Fonts (ออฟไลน์/Private)
ดาวน์โหลดไฟล์ .woff2 จาก google-webfonts-helper แล้วใช้ @font-face ใน CSS ของตัวเอง - เหมาะสำหรับ Intranet หรือต้องการควบคุม Cache เอง