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

การระบุกฎการแบ่งคำ (Word Breaking Rules) ด้วย CSS3

Word-break Property: ควบคุมการขึ้นบรรทัดใหม่ของข้อความยาว

Property word-break กำหนดว่าข้อความยาว (URL, คำยาว, string ไม่มี space) จะขึ้นบรรทัดใหม่อย่างไรเมื่อพื้นที่ไม่พอ

โค้ดตัวอย่าง

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    span { display: inline-block; font-weight: bold; font-size: 20px; margin-right: 20px; }
    div { width: 50px; border: 3px solid #3008c0; margin: 10px; padding: 10px; font-size: 18px; display: inline-block; margin-right: 20px; }
    .normal { word-break: normal; }
    .break-all { word-break: break-all; }
    .break-word { word-break: break-word; } /* deprecated alias of overflow-wrap */
  </style>
</head>
<body>
  <h1>Word Breaking Rules Example</h1>
  <span>NORMAL</span> <span>BREAK ALL</span> <span>BREAK WORD</span><br />
  <div class="normal">Lorem ipsum dolor sit amet consectetur adipisicing elit.</div>
  <div class="break-all">Lorem ipsum dolor sit amet consectetur adipisicing elit.</div>
  <div class="break-word">Lorem ipsum dolor sit amet consectetur adipisicing elit.</div>
</body>
</html>

ค่า word-break

Valueพฤติกรรม
normalขึ้นบรรทัดใหม่เฉพาะจุดที่อนุญาต (space, hyphen) – default
break-allขึ้นบรรทัดใหม่ที่ตัวอักษรใดก็ได้ – อาจตัดคำกลางคำ
keep-allไม่แบ่งคำ CJK (Chinese/Japanese/Korean) – ควบคู่ word-break: normal สำหรับ non-CJK
break-wordเหมือน overflow-wrap: anywhere – แบ่งคำก็ต่อเมื่อจำเป็น (legacy)

ความแตกต่าง: word-break vs overflow-wrap

  • word-break: break-all – บังคับแบ่งทุกโอกาส (aggressive)
  • overflow-wrap: break-word (เดิม word-wrap) – แบ่งก็ต่อเมื่อคำยาวเกิน container (gentle)
  • แนะนำ: ใช้ overflow-wrap: break-word (หรือ anywhere) สำหรับข้อความทั่วไป

รวมกับ Hyphens

.hyphenate {
  overflow-wrap: break-word;
  hyphens: auto; /* ใส่ hyphen (-) ตอนขึ้นบรรทัดใหม่ ต้องมี lang attribute */
}