Khi văn bản dài hơn container, CSS3 cung cấp text-overflow để chỉ định cách hiển thị: cắt ngang (clip) hoặc thêm dấu ba chấm (ellipsis).
Ví dụ mã nguồn
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
.text-box {
white-space: nowrap; /* Bắt buộc: không xuống dòng */
width: 200px;
overflow: hidden; /* Bắt buộc: ẩn phần tràn */
border: 1px solid #3008c0;
margin: 10px 0;
padding: 10px;
background: #fafafa;
}
.clip { text-overflow: clip; } /* Cắt ngang tại giới hạn */
.ellipsis { text-overflow: ellipsis; } /* Thêm "..." */
.ellipsis-custom {
text-overflow: "…➤"; /* Tùy chỉnh string (Firefox only) */
}
</style>
</head>
<body>
<h1>Handling Text Overflow</h1>
<div class="text-box clip">Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum, beatae.</div>
<div class="text-box ellipsis">Lorem ipsum dolor sit amet consectetur adipisicing elit. Rerum, beatae.</div>
<div class="text-box ellipsis-custom">Custom ellipsis string...</div>
</body>
</html>
3 điều kiện BẮT BUỘC cho text-overflow
white-space: nowrap(hoặcpre,pre-wrapvớioverflow)overflow: hidden | scroll | auto(không đượcvisible)widthhoặcmax-widthxác định (không phải auto)
Multiple-line Ellipsis (Hàng 2, 3... dòng) - Line Clamping
/* WebKit/Blink (Chrome, Safari, Edge) - Hỗ trợ tốt */
.line-clamp-2 {
display: -webkit-box;
-webkit-line-clamp: 2; /* Số dòng */
-webkit-box-orient: vertical;
overflow: hidden;
}
/* Chuẩn CSS (đang triển khai) */
.line-clamp-standard {
display: -webkit-box; /* Cần cho compat */
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
/* Tương lai: line-clamp: 3; (chưa hỗ trợ rộng) */
}
Ứng dụng thực tế
- Card title/excerpt giới hạn 1-3 dòng
- Navigation menu item dài
- Table cell content
- Tooltip, popover text
- Breadcrumb path
Lưu ý
text-overflow: ellipsischỉ hoạt động 1 dòng- Multiple lines cần
-webkit-line-clamp(non-standard nhưng support rộng) - RTL languages: ellipsis hiển thị ở bên trái
- Không thể style màu/độ dày của "..." (trừ Firefox
text-overflow: "custom")