Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

นิยามแบบอักษรด้วย CSS @font-face rule


กฎ @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) แล้ว fallback
  • fallback - คอมโปรไมส์
  • optional - ใช้ fallback ถ้า network ช้า