คุณสมบัติ font-size ใน CSS สามารถกำหนดด้วยคีย์เวิร์ดแบบ Absolute (ขนาดคงที่) และ Relative (สัมพัทธ์กับพาเรนต์) เพื่อปรับขนาดข้อความตามต้องการ
ไวยากรณ์ (Syntax)
Selector {
font-size: /*value*/;
}
ตารางคีย์เวิร์ดมาตรฐาน
| ลำดับ | ค่า & คำอธิบาย |
|---|---|
| 1 | medium - ขนาดกลาง (ค่าเริ่มต้น) |
| 2 | xx-small - ขนาด xx-small |
| 3 | x-small - ขนาด extra small |
| 4 | small - ขนาด small |
| 5 | large - ขนาด large |
| 6 | x-large - ขนาด extra-large |
| 7 | xx-large - ขนาด xx-large |
| 8 | smaller - ขนาดเล็กกว่าพาเรนต์ |
| 9 | larger - ขนาดใหญ่กว่าพาเรนต์ |
ตัวอย่างที่ 1: Larger, Medium, Xx-large
<!DOCTYPE html>
<html>
<head>
<style>
h1 { font-size: larger; }
#demo { font-size: medium; text-align: center; background-color: floralwhite; }
p { font-size: xx-large; }
</style>
</head>
<body>
<h1>Demo Heading</h1>
<p id="demo">This is demo text.</p>
<p>This is another demo text.</p>
</body>
</html>
ผลลัพธ์

ตัวอย่างที่ 2: Xx-small พาเรนต์ และ Xx-large ลูก
<!DOCTYPE html>
<html>
<head>
<style>
div { margin: auto; padding: 5px; width: 30%; border: 1px solid; border-radius: 29%; text-align: center; font-size: xx-small; }
p { font-size: xx-large; }
</style>
</head>
<body>
<div>
<div>One</div>
<p>Two</p>
</div>
</body>
</html>
ผลลัพธ์

ขนาดสัมพัทธ์ (Relative Sizing)
คีย์เวิร์ด smaller และ larger คำนวณจากขนาดฟอนต์ของพาเรนต์:
body { font-size: 16px; } /* base */
h1 { font-size: larger; } /* ~1.2em = 19.2px */
h2 { font-size: larger; } /* ~1.2em = 19.2px */
small { font-size: smaller; } /* ~0.85em = 13.6px */
สเกลตัวแปร (Scaling Factor) ประมาณ
| Keyword | Ratio (approx) | จาก 16px |
|---|---|---|
| xx-small | 0.625 | 10px |
| x-small | 0.75 | 12px |
| small | 0.875 | 14px |
| medium | 1.0 | 16px |
| large | 1.2 | 19.2px |
| x-large | 1.5 | 24px |
| xx-large | 2.0 | 32px |
| larger | ×1.2 | ขึ้น 1 ระดับ |
| smaller | ×0.85 | ลง 1 ระดับ |
แนวทาง Modern: ใช้ rem แทน Keywords
:root { font-size: 100%; } /* 16px baseline */
h1 { font-size: 2.5rem; } /* 40px */
h2 { font-size: 2rem; } /* 32px */
h3 { font-size: 1.5rem; } /* 24px */
body { font-size: 1rem; } /* 16px */
small { font-size: 0.875rem; } /* 14px */
.large { font-size: 1.25rem; } /* 20px */
ข้อดีของ rem: คำนวณง่าย สม่ำเสมอ ไม่สะสม (no compounding) รองรับการปรับขนาดของผู้ใช้ได้ดี