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

การจัดตำแหน่งข้อความแนวนอนด้วย CSS text-align

คุณสมบัติ text-align ใน CSS ใช้จัดตำแหน่งข้อความแนวนอนภายในองค์ประกอบ ได้ค่า left, right, center, justify

ไวยากรณ์ (Syntax)

Selector {
  text-align: /*value*/;
}

ตัวอย่างที่ 1: จัดข้อความใน div ต่างๆ

<!DOCTYPE html>
<html>
<head>
  <style>
    div {
      margin: auto; padding: 8px; max-width: 200px; border: thin solid;
    }
    p { text-align: right; }
    div:nth-child(3) { text-align: center; }
    div:last-child { text-align: justify; }
  </style>
</head>
<body>
  <h2>Student Examination Details</h2>
  <div>
    <div>Student John</div>
    <div> Student Tom <p>Did not appeared for the exams.</p> </div>
    <div>Student Brad</div>
    <div>Did not appeared for only the last exam.</div>
  </div>
</body>
</html>

ผลลัพธ์

การจัดตำแหน่งข้อความแนวนอนด้วย CSS text-align

ตัวอย่างที่ 2: จัดข้อความในตาราง

<!DOCTYPE html>
<html>
<head>
  <style>
    td { padding: 10px; box-shadow: inset 0 0 21px yellow; }
    td:first-of-type { text-align: right; }
  </style>
</head>
<body>
  <h2>Demo Heading</h2>
  <table>
    <tr><td>This is it!</td></tr>
    <tr><td>Well, this is a demo text!</td></tr>
  </table>
</body>
</html>

ผลลัพธ์

การจัดตำแหน่งข้อความแนวนอนด้วย CSS text-align

ค่าของ text-align

ค่าคำอธิบาย
leftชิดซ้าย (ค่าเริ่มต้นสำหรับ LTR)
rightชิดขวา
centerกึ่งกลาง
justifyจัดเต็มทั้งซ้ายและขวา (ยกเว้นบรรทัดสุดท้าย)
startชิดจุดเริ่มต้นตามทิศทางการเขียน (LTR=ซ้าย, RTL=ขวา)
endชิดจุดสิ้นสุดตามทิศทางการเขียน
match-parentสืบทอดจากพาเรนต์ แต่แปลง start/end ตาม direction

ข้อควรระวัง

  • text-align ส่งผลต่อ inline/inline-block content ภายในบล็อก ไม่ใช่บล็อกตัวเอง
  • เพื่อจัดบล็อกให้กึ่งกลาง ใช้ margin: 0 auto (ต้องมี width)
  • justify อาจสร้างช่องว่างใหญ่ผิดปกติในภาษาที่ไม่เว้นวรรค (ไทย, จีน) ควรใช้ text-justify: inter-character ร่วมกัน