หน่วยความยาวแบบสัมพัทธ์ (Relative Length Units) ระบุขนาดเทียบกับขนาดอื่นๆ เช่น ขนาดฟอนต์, viewport, parent element
ตารางหน่วยความยาวแบบสัมพัทธ์
| ลำดับ | หน่วย | คำอธิบาย |
|---|---|---|
| 1 | em | เทียบกับ font-size ของ element นั้นๆ (4em = 4x font-size ปัจจุบัน) |
| 2 | ex | เทียบกับ x-height ของฟอนต์ปัจจุบัน (ความสูงตัว 'x') |
| 3 | ch | เทียบกับความกว้างของตัวอักษร '0' (zero) |
| 4 | rem | เทียบกับ font-size ของ root element (<html>) |
| 5 | vw | 1% ของความกว้าง viewport (viewport width) |
| 6 | vh | 1% ของความสูง viewport (viewport height) |
| 7 | vmin | 1% ของมิติเล็กกว่าของ viewport (min(width, height)) |
| 8 | vmax | 1% ของมิติใหญ่กว่าของ viewport (max(width, height)) |
| 9 | % | เทียบกับ parent element (ขึ้นอยู่กับคุณสมบัติที่ใช้) |
ตัวอย่างที่ 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>
คำอธิบายและแนวทางการใช้งาน
em vs rem:
| ด้าน | em | rem |
|---|---|---|
| อ้างอิง | font-size ของ element ตัวเอง (สืบทอดมา) | font-size ของ root (html) เสมอ |
| การซ้อน (nesting) | คูณซ้อนกัน (compounding) | ไม่ซ้อน คงที่เสมอ |
| เหมาะสำหรับ | component scaling, spacing ภายใน component | layout ทั่วไป, typography system |
Viewport Units (vw, vh, vmin, vmax):
- เหมาะสำหรับ full-screen layouts, hero sections
100vh= ความสูงเต็มหน้าจอ (ระวัง address bar บน mobile)- CSS มีหน่วยใหม่:
svh,lvh,dvh(small/large/dynamic viewport)
ch (Character):
เหมาะสำหรับจำกัดความกว้างข้อความ (optimal line length ~ 60-75ch)
% (Percent):
ขึ้นอยู่กับคุณสมบัติ: width/height = % ของ parent, font-size = % ของ parent font-size, margin/padding = % ของ parent width (แม้แนวตั้ง!)