CSS Text Overflow
What is Text Overflow in CSS?
The text-overflow property is used to control how text content should behave when it overflows its containing element.
It is commonly used in conjunction with the white-space and overflow properties.
Text Overflow with Ellipsis:
Here, text is not allowed to wrap to the next line, hides any content that exceeds the container will be shown along with an ellipsis (...) and so content will be shown.
div {
white-space: nowrap; /* Prevents the text from wrapping to the next line */
overflow: hidden; /* Hides any content that overflows the container */
text-overflow: ellipsis; /* Displays an ellipsis (...) when text overflows */
}
Text Overflow with Custom String:
div {
white-space: nowrap;
overflow: hidden;
text-overflow: "Read more"; /* Displays "Read more" when text overflows */
}
You can use a custom string instead of an ellipsis.
Text Overflow in Multi-Line Text:
div {
display: -webkit-box;
-webkit-line-clamp: 3; /* Limit the number of lines to 3 */
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
}
This example limits the number of displayed lines to 3 and adds an ellipsis for multi-line text.
Text Overflow with Clip:
div {
white-space: nowrap;
overflow: hidden;
text-overflow: clip; /* Clips the text without displaying an ellipsis */
}
This example clips the text without displaying an ellipsis.
Text Overflow in Table Cells:
td {
max-width: 100px; /* Set a maximum width for the table cell */
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
This example uses text-overflow in a table cell to add ellipsis to long text.
Responsive Text Overflow:
div {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
width: 100%; /* Responsive width */
box-sizing: border-box; /* Include padding and border in the total width */
}
By setting the width to 100%, farther along, the text and images responsively becomes overflowed. This is achieved through using a pixel-based design technique known as box-sizing, which includes padding and border in the total width calculation.