It is a method to omit the text that overflows due to the large number of characters from the specified width in CSS with a three-point reader (…).
Now, even multiple lines can be implemented with CSS only. I feel like I used to use jQuery or something to mess up.
JavaScript implementation is still recommended for proper support with older browsers, but for modern browsers only, CSS alone is easier.
Omit the text that extends in CSS. For one line
Use text-overflow
.
Reference ⇒text-overflow | MDN
There are a few rules when using it.
-Use with overflow: hidden;
and white-space: nowrap;
-Text-overflow is effective for text that extends inline (horizontally) to the Block element.
BLOCK element sample
CODE
// HTML <div class="text-overflow" style="max-width: 200px;"> This is a test that omits the text that sticks out in CSS. </div> // CSS .text-overflow { text-overflow: ellipsis; overflow: hidden; white-space: nowrap; }
TABLE sample
You can also use it with the table-cell
attribute, but there are some caveats.
You must also specify width
in the table
itself.
If specified, it may be width: 100%;
. It is omitted when it extends beyond td.
This is a test that omits the text that sticks out in CSS. |
CODE
// HTML <table style="max-width: 200px;"> <tr> <td class="text-overflow" style="max-width: 200px;"> This is a test that omits the text that sticks out in CSS.This is a test that omits the text that sticks out in CSS.This is a test that omits the text that sticks out in CSS. </td> </tr> </table>
text-overflow doesn’t work?
Recently, there are more and more cases where flex is used with display: flex;
when building a layout.If the element for which text-overflow
is specified is flex, text omission will not work.
So when you use it, you should enclose it in div
.
How to omit when the text extends over multiple lines
This is only compatible with modern browsers. (Chrome, safari)
Multi-line sample
CODE
// HTML <div class="text-overflow-lines" style="max-width: 200px;"> This is a test that omits the text that sticks out in CSS.This is a test that omits the text that sticks out in CSS.This is a test that omits the text that sticks out in CSS.This is a test that omits the text that sticks out in CSS. </div> // CSS .text-overflow-lines { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 3; overflow: hidden; }
Nowadays, there is display: flex;
, so webkit-box has no place to play, but there was such a use.