CSS Absolute Units (หน่วยสัมบูรณ์)
หน่วยความยาวแบบสัมบูรณ์มีค่าคงที่สัมพันธ์กัน ใช้เมื่อรูปแบบเอาต์พุททราบล่วงหน้า หน่วยหลักมีดังนี้:
| ลำดับ | หน่วยและคำอธิบาย |
|---|---|
| 1 | cm - เซนติเมตร |
| 2 | mm - มิลลิเมตร |
| 3 | in - นิ้ว (1in = 96px = 2.54cm) |
| 4 | px - พิกเซล (1px = 1/96 ของ 1in) * หน่วยหลักหน้าจอ |
| 5 | pt - พอยต์ (1pt = 1/72 ของ 1in) ใช้ในพิมพ์ |
| 6 | pc - ไพคา (1pc = 12 pt) ใช้ในพิมพ์ |
ตัวอย่าง: ใช้หน่วยนิ้ว (in)
<!DOCTYPE html> <html> <head> <style> .demo { text-decoration: overline underline; text-decoration-color: blue; font-size: 0.3in; } </style> </head> <body> <h1>Details</h1> <p class="demo">Examination Center near ABC College.</p> <p class="demo2">Exam begins at 9AM.</p> </body> </html>
ผลลัพธ์

CSS Relative Units (หน่วยสัมพัทธ์)
หน่วยความยาวแบบสัมพัทธ์ใน CSS ใช้ระบุความยาวสัมพันธ์กับคุณสมบัติความยาวอื่น
| ลำดับ | หน่วยและคำอธิบาย |
|---|---|
| 1 | em - สัมพันธ์กับ font-size ขององค์ประกอบตัวเอง (4em = 4× font-size ปัจจุบัน) |
| 2 | ex - สัมพันธ์กับ x-height ของฟอนต์ปัจจุบัน (ความสูงตัว 'x') |
| 3 | ch - สัมพันธ์กับความกว้างของตัวอักษร '0' (zero) |
| 4 | rem - สัมพันธ์กับ font-size ของ root element (:root หรือ html) |
| 5 | vw - สัมพันธ์กับ 1% ของความกว้าง viewport |
| 6 | vh - สัมพันธ์กับ 1% ของความสูง viewport |
| 7 | vmin - สัมพันธ์กับ 1% ของมิติเล็กกว่าของ viewport |
| 8 | vmax - สัมพันธ์กับ 1% ของมิติใหญ่กว่าของ viewport |
| 9 | % - สัมพันธ์กับองค์ประกอบพ่อ (context ขึ้นกับคุณสมบัติ) |
ตัวอย่างที่ 1: ใช้ em
<!DOCTYPE html> <html> <head> <style> .demo { text-decoration: overline underline; text-decoration-color: blue; font-size: 1.4em; } </style> </head> <body> <h1>Details</h1> <p class="demo">Examination Center near ABC College.</p> <p class="demo2">Exam begins at 9AM.</p> </body> </html>
ผลลัพธ์

ตัวอย่างที่ 2: ใช้ ch
<!DOCTYPE html> <html> <head> <style> .demo { text-decoration: overline underline; text-decoration-color: blue; font-size: 4ch; } </style> </head> <body> <h1>Details</h1> <p class="demo">Examination Center near ABC College.</p> <p class="demo2">Exam begins at 9AM.</p> </body> </html>
ผลลัพธ์

คำแนะนำการเลือกใช้
| หน่วย | เหมาะสำหรับ | ข้อควรระวัง |
|---|---|---|
| rem | font-size ทั่วไป, spacing system | อ้างอิง root ไม่ซ้อนกัน |
| em | padding, margin, การ scale ภายใน component | สะสม (compound) เมื่อซ้อนลึก |
| ch | ความกว้างข้อความ, max-width อ่านสบาย | ขึ้นกับฟอนต์ (monospace แม่นยำกว่า) |
| vw/vh | Full-screen layout, hero section | ระวัง scrollbar, mobile keyboard |
| % | width, height, margin, padding (layout) | อ้างอิงพ่อ context เปลี่ยนได้ |