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

การจัดการ Text Overflow ใน CSS3

Text-overflow: จัดการข้อความล้นพื้นที่ (Ellipsis/Clip)

Property text-overflow ควบคุมการแสดงเมื่อข้อความยาวกว่ากล่อง (ต้องใช้ร่วม white-space: nowrap + overflow: hidden)

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

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    div {
      white-space: nowrap; width: 100px; overflow: hidden;
      border: 1px solid #3008c0; margin: 10px; padding: 10px; font-size: 18px; display: inline-block; margin-right: 20px;
    }
    .clip { text-overflow: clip; }
    .ellipsis { text-overflow: ellipsis; }
  </style>
</head>
<body>
  <h1>Handling Text Overflow Example</h1>
  CLIP: <div class="clip"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum, beatae. </div>
  ELLIPSIS: <div class="ellipsis"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum, beatae. </div>
</body>
</html>

ค่า text-overflow

  • clip (default) – ตัดทิ้งทันทีที่ขอบ
  • ellipsis – แสดง … (U+2026) ท้ายข้อความที่ล้น
  • string (experimental) – string กำหนดเอง เช่น text-overflow: " [more]"; (Firefox behind flag)

เงื่อนไขจำเป็น (Required)

.truncate {
  white-space: nowrap;      /* ห้าม wrap */
  overflow: hidden;         /* ซ่อนส่วนล้น */
  text-overflow: ellipsis;  /* แสดง ... */
}

Multi-line Ellipsis (หลายบรรทัด)

CSS ไม่มี property ตรงสำหรับ multi-line ellipsis ใช้ -webkit-line-clamp:

.multi-line {
  display: -webkit-box;
  -webkit-line-clamp: 3;     /* จำนวนบรรทัด */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;   /* สำหรับบรรทัดสุดท้าย */
}

รองรับ Chrome, Safari, Edge, Firefox 68+

Accessibility

Ellipsis อาจทำให้ screen reader อ่านไม่ครบ – ให้เต็มข้อความใน title attribute หรือ aria-label หรือมีปุ่ม "Read more"