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

หน่วยความยาวแบบสัมพัทธ์ (Relative Length Units) ใน CSS

หน่วยความยาวแบบสัมพัทธ์ (Relative Length Units) ระบุขนาดเทียบกับขนาดอื่นๆ เช่น ขนาดฟอนต์, viewport, parent element

ตารางหน่วยความยาวแบบสัมพัทธ์

ลำดับหน่วยคำอธิบาย
1emเทียบกับ font-size ของ element นั้นๆ (4em = 4x font-size ปัจจุบัน)
2exเทียบกับ x-height ของฟอนต์ปัจจุบัน (ความสูงตัว 'x')
3chเทียบกับความกว้างของตัวอักษร '0' (zero)
4remเทียบกับ font-size ของ root element (<html>)
5vw1% ของความกว้าง viewport (viewport width)
6vh1% ของความสูง viewport (viewport height)
7vmin1% ของมิติเล็กกว่าของ viewport (min(width, height))
8vmax1% ของมิติใหญ่กว่าของ 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:

ด้านemrem
อ้างอิงfont-size ของ element ตัวเอง (สืบทอดมา)font-size ของ root (html) เสมอ
การซ้อน (nesting)คูณซ้อนกัน (compounding)ไม่ซ้อน คงที่เสมอ
เหมาะสำหรับcomponent scaling, spacing ภายใน componentlayout ทั่วไป, 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 (แม้แนวตั้ง!)