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

การตั้งค่าความสูงบรรทัดด้วย CSS (line-height)

เพื่อตั้งค่าความสูงบรรทัด ให้ใช้คุณสมบัติ line-height ค่าที่ใช้ได้มีดังนี้:

line-height: normal | number | length | percentage | initial | inherit;

ตัวอย่างที่ 1: ใช้ตัวเลข (unitless) - แนะนำ

<!DOCTYPE html> <html> <head> <style> div {    line-height: 1.9; } </style> </head> <body> <h1>Demo Heading</h1> <div> <p>This is demo text.<br> This is another demo text. </p> </div> </body> </html>

ผลลัพธ์

การตั้งค่าความสูงบรรทัดด้วย CSS (line-height)

ตัวอย่างที่ 2: ใช้เปอร์เซ็นต์

<!DOCTYPE html> <html> <head> <style> div {    line-height: 200%; } </style> </head> </head> <body> <h1>Demo Heading</h1> <div> <p>This is demo text.<br> This is another demo text. </p> </div> </body> </html>

ผลลัพธ์

การตั้งค่าความสูงบรรทัดด้วย CSS (line-height)

ความแตกต่างของหน่วย (สำคัญ!)

หน่วยการคำนวณสืบทอดให้ลูกแนะนำ
number (unitless)font-size × numberคูณกับ font-size ของลูก (ดีที่สุด)✅ แนะนำมากที่สุด
length (px, em, rem)ค่าคงที่ค่าคงที่ (อาจแคบเกินไป)ใช้ได้แต่ระวัง
percentage (%)font-size × percentageค่าคงที่ (คำนวณครั้งเดียวที่พ่อ)ไม่แนะนำ
normalขึ้นกับฟอนต์ (~1.2)ตามฟอนต์ของลูกค่าเริ่มต้น

ตัวอย่างปัญหา percentage/length

/* พ่อ font-size: 20px, line-height: 150% = 30px */
.parent { font-size: 20px; line-height: 150%; }
.child { font-size: 40px; } /* line-height ยังคง 30px! แคบเกินไป */

แนวทางปฏิบัติที่ดี

  • ใช้ unitless number (เช่น 1.5, 1.6) สำหรับ body text
  • ค่าทั่วไป: 1.5-1.7 สำหรับเนื้อหาอ่าน (readability)
  • หัวข้อ (heading) ใช้ค่าน้อยกว่า: 1.2-1.3
  • ตั้งค่าที่ body หรือ :root เพื่อสืบทอดให้ทั้งหน้า