This article describes how to truncate text that overflows its defined width in CSS with an ellipsis (...).
Nowadays, it's possible to implement this with CSS alone, even for multiple lines. I remember how messy it used to be, often involving jQuery.
While JavaScript implementation is still recommended for proper support across older browsers, if you're targeting only modern browsers, using CSS alone is simpler.
TRUNCATING OVERFLOWING TEXT WITH CSS: SINGLE LINE
・Use in conjunction with `overflow: hidden;` and `white-space: nowrap;`
・`text-overflow` is effective for text that overflows inline (horizontally) within block elements.
Block Element Sample
This is a test to truncate overflowing text with CSS. This is a test to truncate overflowing text with CSS.
Code
// HTML
<div class="text-overflow" style="max-width: 200px;">
CSSではみ出したテキストを省略するテストです。
</div>
// CSS
.text-overflow {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}Table Sample
It can also be used with `table-cell` attributes, but there are some caveats.
You can use `width: 100%;` or similar if specified. The text will be truncated once it overflows the `td`.
Code
// HTML
<table style="max-width: 200px;">
<tr>
<td class="text-overflow" style="max-width: 200px;">
CSSではみ出したテキストを省略するテストです。CSSではみ出したテキストを省略するテストです。CSSではみ出したテキストを省略するテストです。
</td>
</tr>
</table>TEXT-OVERFLOW NOT WORKING OR EFFECTIVE?
Recently, the use of `display: flex;` for layout has become more common. A common pitfall is that `text-overflow` won't work for text truncation if the element it's applied to is a flex item.
HOW TO TRUNCATE OVERFLOWING TEXT ACROSS MULTIPLE LINES
This method is supported only by modern browsers (Chrome, Safari).
Multi-line Sample
This is a test to truncate overflowing text with CSS. This is a test to truncate overflowing text with CSS. This is a test to truncate overflowing text with CSS. This is a test to truncate overflowing text with CSS.
Code
// HTML
<div class="text-overflow-lines" style="max-width: 200px;">
CSSではみ出したテキストを省略するテストです。CSSではみ出したテキストを省略するテストです。CSSではみ出したテキストを省略するテストです。CSSではみ出したテキストを省略するテストです。
</div>
// CSS
.text-overflow-lines {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3;
overflow: hidden;
}While Flexbox, as in `display: -webkit-box;`, might seem to have lost its place with the advent of `display: flex;`, it certainly had its uses, as shown here.
The above method is based on the following website, which also describes how to support browsers other than modern ones.
【Supports multiple lines】Various ways to truncate long strings with an ellipsis (...) at the end
RECOMMENDED BOOKS FOR CSS/SASS
For CSS and SCSS, once you understand the basics, it's often quicker to look things up with Google Sensei. Just grasping the mechanisms of CSS and how to use SASS is generally sufficient.
HTML & CSS and Web Design Introductory Course: Learn Everything in One Book
📦