คุณสมบัติ font-size กำหนดขนาดตัวอักษร รองรับหน่วย: px, em, rem, %, pt, cm, keyword (small, large, x-large, ฯลฯ) ค่าเริ่มต้น 16px (หรือ 12pt)
Syntax
Selector { font-size: <value>; }
ตัวอย่างที่ 1: ใช้ em (Relative)
<!DOCTYPE html> <html> <head> <style> div { margin: auto; padding: 10px; text-align: center; width: 50%; border: 2px solid; border-radius: 15%; font-size: 1.4em; } </style> </head> <body> <div> one <div>two <div>three</div> </div> </div> </body> </html>
ตัวอย่างที่ 2: Keywords และ Percentage
<!DOCTYPE html> <html> <head> <style> p { font-size: smaller; } #demo { font-size: initial; } p:last-of-type { font-size: 200%; } </style> </head> <body> <h2>Demo Heading</h2> <p>This is demo text 1.</p> <p id="demo">This is demo text 2. </p> <p>This is demo text 3.</p> </body> </html>
คำอธิบาย
ตัวอย่างที่ 1: font-size: 1.4em บน div ภายนอก แล้ว nested div ภายในจะสืบทอดและคูณซ้อน (compounding) ทำให้ขนาดใหญ่ขึ้นเรื่อยๆ
ตัวอย่างที่ 2: smaller (เล็กลง 1 ขนาดจาก parent), initial (คืนค่าเริ่มต้น 16px), 200% (ใหญ่ 2 เท่าของ parent)
หน่วยขนาดฟอนต์:
| ประเภท | หน่วย | คำอธิบาย |
|---|---|---|
| Absolute | px | พิกเซล คงที่ ไม่ยืดหยุ่น |
pt | พอยต์ (1pt = 1/72 inch) ใช้สำหรับ print | |
pc | ไพคา (1pc = 12pt) | |
cm, mm, in | เซนติเมตร, มิลลิเมตร, นิ้ว | |
| Relative | em | เทียบกับ font-size ของ element (compounding) |
rem | เทียบกับ root font-size (html) ไม่ซ้อน | |
% | เทียบกับ parent font-size | |
ex | เทียบกับ x-height | |
ch | เทียบกับความกว้าง '0' | |
| Keyword | xx-small - xx-large | 7 ระดับ: xx-small, x-small, small, medium, large, x-large, xx-large |
smaller | เล็กลง 1 ขนาดจาก parent | |
larger | ใหญ่ขึ้น 1 ขนาดจาก parent | |
initial | คืนค่าเริ่มต้น | |
inherit | สืบทอดจาก parent | |
unset | inherit ถ้าสืบทอดได้ ไม่งั้น initial |
แนวทางปฏิบัติที่ดี (Best Practices):
- ใช้
remสำหรับ font-size หลัก (consistent, accessible) - ตั้ง
html { font-size: 100%; }(16px baseline) แล้วใช้ rem ทุกที่ - ใช้
emสำหรับ spacing ภายใน component (padding, margin) - หลีกเลี่ยง px สำหรับ font-size (ไม่เคารพ user preference)
- ใช้
clamp()สำหรับ fluid typography:font-size: clamp(1rem, 2vw + 1rem, 2rem);