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

คุณสมบัติ CSS hyphens สำหรับการขีดคั่นคำ (Hyphenation)

คุณสมบัติ hyphens ควบคุมการขีดคั่นคำ (hyphenation) เมื่อข้อความ wrap ไปบรรทัดใหม่ ช่วยให้ข้อความจัดเรียงสวยงามขึ้น (justified text)

ค่าที่ใช้ได้

hyphens: none | manual | auto | initial | inherit;
  • none: ไม่ขีดคั่นคำเลย (คำยาวจะล้นออกไป)
  • manual (default): ขีดคั่นเฉพาะที่มี ‐ (soft hyphen: ­ หรือ \u00AD) ใน HTML
  • auto: บราวเซอร์ขีดคั่นอัตโนมัติตามกฎภาษา (ต้องมี lang attribute)

ตัวอย่างที่ 1: hyphens: manual

<!DOCTYPE html>
<html>
<head>
  <style>
    div { width: 50px; border: 2px dashed red; }
    .demo { 
      -webkit-hyphens: manual; 
      -ms-hyphens: manual; 
      hyphens: manual; 
    }
  </style>
</head>
<body>
  <h1>Demo Heading</h1>
  <h2>hyphens: manual property value</h2>
  <div class="demo">This is a demo text.</div>
</body>
</html>

ตัวอย่างที่ 2: hyphens: auto (ต้องมี lang attribute)

<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    div { width: 50px; border: 2px dashed red; color: blue; }
    .demo { 
      -webkit-hyphens: auto; 
      -ms-hyphens: auto; 
      hyphens: auto; 
    }
  </style>
</head>
<body>
  <h1>Demo Heading</h1>
  <h2>hyphens: auto property value</h2>
  <div class="demo">This isssssss a demo text.</div>
</body>
</html>

ข้อสำคัญ: hyphens: auto ต้องการ lang attribute บน <html> หรือ element ancestor เพื่อให้บราวเซอร์รู้กฎภาษา (ไทยต้องมี lang="th" แต่รองรับภาษาไทยอาจไม่สมบูรณ์)

Prefix: Safari/iOS ต้องใช้ -webkit-hyphens IE/Edge เก่าใช้ -ms-hyphens

การประยุกต์: ใช้ auto สำหรับบทความยาว, justified text ใช้ manual สำหรับคำเฉพาะที่ต้องการควบคุมจุดขีดคั่น