@font-face สำหรับดาวน์โหลดฟอนต์
กฎ @font-face ใช้กำหนดที่ตั้ง (location) ของไฟล์ฟอนต์เพื่อให้เบราว์เซอร์ดาวน์โหลดมาใช้ แม้จะอาจมีข้อจำกัดจากการติดตั้ง (implementation-specific limits)
ตัวอย่าง
<style>
@font-face {
font-family: "Scarborough Light";
src: url("https://www.font.site/s/scarbo-lt");
}
@font-face {
font-family: Santiago;
src: local("Santiago"),
url("https://www.font.site/s/santiago.tt") format("truetype");
unicode-range: U+??, U+100-220;
font-size: all;
font-family: sans-serif;
}
</style>
คำอธิบาย src แบบละเอียด
/ รูปแบบเดียว /
src: url("font.woff2") format("woff2");
/ หลายรูปแบบ (Fallback chain) - โหลดตัวแรกที่รองรับ /
src:
url("font.woff2") format("woff2"),
url("font.woff") format("woff"),
url("font.ttf") format("truetype"),
url("font.eot") format("embedded-opentype");
/ ร่วมกับ local() - ใช้ฟอนต์ในระบบถ้ามี /
src:
local("Helvetica Neue"),
local("HelveticaNeue"),
url("helvetica.woff2") format("woff2");
รูปแบบไฟล์ฟอนต์และการรองรับ
| รูปแบบ | format() | การรองรับ |
|---|---|---|
| WOFF2 | woff2 | ทุกเบราว์เซอร์สมัยใหม่ (Best compression) |
| WOFF | woff | เก่ากว่า WOFF2 |
| TrueType | truetype | เก่า รองรับกว้าง |
| OpenType | opentype | เช่น TTF/OTF |
| EOT | embedded-opentype | IE เท่านั้น (Legacy) |
unicode-range: เพิ่มประสิทธิภาพการโหลด
@font-face {
font-family: 'Noto Sans';
src: url('noto.woff2') format('woff2');
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
/* Latin only - ไม่โหลดสำหรับภาษาอื่น */
}
ข้อควรระวัง
- License: ตรวจสอบสิทธิ์การใช้ฟอนต์บนเว็บ (Webfont license)
- Performance: ใช้ WOFF2, unicode-range, font-display: swap
- Fallback: กำหนด system font stack เสมอ