กฎ @font-face
ใช้ @font-face เพื่ออธิบายลักษณะแบบอักษร (font face) อย่างครบถ้วนสำหรับใช้ในเอกสาร รวมถึงกำหนดที่ตั้งไฟล์เพื่อดาวน์โหลด
ตัวอย่างการใช้งาน
<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; /* fallback - หมายเหตุ: ควรเป็น font-family ตัวสำรอง */
}
</style>
คำอธิบายคุณสมบัติ
| คุณสมบัติ | คำอธิบาย |
|---|---|
font-family | ชื่อที่จะใช้เรียกใน CSS (เช่น font-family: 'MyFont') |
src | ที่อยู่ไฟล์: url() หรือ local() (ฟอนต์ในระบบ) |
format() | รูปแบบไฟล์: truetype, opentype, woff, woff2, embedded-opentype |
unicode-range | ช่วง Unicode ที่ฟอนต์ครอบคลุม (โหลดเฉพาะที่ต้องใช้) |
font-weight | น้ำหนัก: normal, bold, 100-900 |
font-style | สไตล์: normal, italic, oblique |
font-stretch | ความกว้าง: normal, condensed, expanded |
รูปแบบแนะนำสมัยใหม่ (Modern Best Practice)
@font-face {
font-family: 'Inter';
src: url('inter-var.woff2') format('woff2-variations');
font-weight: 100 900;
font-display: swap;
font-stretch: 85% 100%;
}
/* Variable Font - ไฟล์เดียวครบทุก weight */
@font-face {
font-family: 'Roboto Flex';
src: url('roboto-flex.woff2') format('woff2-variations');
font-weight: 100 1000;
font-stretch: 25% 151%;
font-style: oblique 0deg 12deg;
font-display: swap;
}
font-display: สำคัญสำหรับ Performance
swap- แสดง fallback ทันที สลับเมื่อโหลดเสร็จ (แนะนำ)block- บล็อกสั้นๆ (3s) แล้ว fallbackfallback- คอมโปรไมส์optional- ใช้ fallback ถ้า network ช้า