The text-overflow property in CSS is used to specify how overflowed content that is not displayed should be signaled to the user. This property is particularly useful for managing text within containers that have a fixed width.
There are three main values for the text-overflow property: clip, ellipsis, and string. Let's dive into each of these with examples.
The clip value is the default value for the text-overflow property. It simply clips the overflowed text without adding any visual indication that the text has overflowed.
<div class="text-clip">
This is some text that will be clipped if it overflows the container.
</div>
.text-clip {
white-space: nowrap;
overflow: hidden;
text-overflow: clip;
width: 200px;
border: 1px solid black;
}
The ellipsis value displays an ellipsis ("...") to represent the clipped text. This is useful when you want to give a visual cue that there is more text than what is displayed.
<div class="text-ellipsis">
This is some text that will show an ellipsis if it overflows the container.
</div>
.text-ellipsis {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
width: 200px;
border: 1px solid black;
}
The string value allows you to specify a custom string to indicate the overflowed text. This can be useful if you want a different visual indicator other than the ellipsis.
<div class="text-string">
This is some text that will show a custom string if it overflows the container.
</div>
.text-string {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
width: 200px;
border: 1px solid black;
position: relative;
}
.text-string::after {
content: '>>> ';
position: absolute;
right: 0;
white-space: nowrap;
background-color: white;
}
Note: The text-overflow property only works for block elements with a specified width and the overflow property set to hidden, scroll, or auto.
.text-important {
width: 150px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
border: 1px solid black;
}
For single-line text overflow, you need to use the white-space property set to nowrap.
<div class="text-single-line">
This is a single line text that will show ellipsis if it overflows.
</div>
.text-single-line {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
width: 200px;
border: 1px solid black;
}
For multi-line text overflow, you can use the overflow-wrap property set to break-word.
<div class="text-multi-line">
This is a multi-line text that will show ellipsis if it overflows.
</div>
.text-multi-line {
overflow: hidden;
text-overflow: ellipsis;
width: 200px;
border: 1px solid black;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
}
By understanding and using the text-overflow property effectively, you can improve the readability and aesthetics of your web pages, especially when dealing with dynamic content.