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

ทำความเข้าใจหน่วย CSS Absolute และ Relative Units

CSS Absolute Units (หน่วยสัมบูรณ์)

หน่วยความยาวแบบสัมบูรณ์มีค่าคงที่สัมพันธ์กัน ใช้เมื่อรูปแบบเอาต์พุททราบล่วงหน้า หน่วยหลักมีดังนี้:

ลำดับหน่วยและคำอธิบาย
1cm - เซนติเมตร
2mm - มิลลิเมตร
3in - นิ้ว (1in = 96px = 2.54cm)
4px - พิกเซล (1px = 1/96 ของ 1in) * หน่วยหลักหน้าจอ
5pt - พอยต์ (1pt = 1/72 ของ 1in) ใช้ในพิมพ์
6pc - ไพคา (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 Absolute และ Relative Units

CSS Relative Units (หน่วยสัมพัทธ์)

หน่วยความยาวแบบสัมพัทธ์ใน CSS ใช้ระบุความยาวสัมพันธ์กับคุณสมบัติความยาวอื่น

ลำดับหน่วยและคำอธิบาย
1em - สัมพันธ์กับ font-size ขององค์ประกอบตัวเอง (4em = 4× font-size ปัจจุบัน)
2ex - สัมพันธ์กับ x-height ของฟอนต์ปัจจุบัน (ความสูงตัว 'x')
3ch - สัมพันธ์กับความกว้างของตัวอักษร '0' (zero)
4rem - สัมพันธ์กับ font-size ของ root element (:root หรือ html)
5vw - สัมพันธ์กับ 1% ของความกว้าง viewport
6vh - สัมพันธ์กับ 1% ของความสูง viewport
7vmin - สัมพันธ์กับ 1% ของมิติเล็กกว่าของ viewport
8vmax - สัมพันธ์กับ 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>

ผลลัพธ์

ทำความเข้าใจหน่วย CSS Absolute และ Relative Units

ตัวอย่างที่ 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>

ผลลัพธ์

ทำความเข้าใจหน่วย CSS Absolute และ Relative Units

คำแนะนำการเลือกใช้

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