text-overflow is a CSS property that defines how text that overflows its container should be handled. It’s commonly used to truncate text with an ellipsis (…), making it ideal for displaying long text within limited space.
How it works:
To effectively use text-overflow, you typically combine it with two other properties:
white-space: nowrap: Prevents text from wrapping to the next line.overflow: hidden: Hides any content that overflows the container.
Basic example:
<div class="truncated-text">This text is too long to fit in the container.</div>
.truncated-text {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
Breakdown of the code:
.truncated-text: This is a CSS class applied to the HTML element.white-space: nowrap: Prevents the text from wrapping to the next line, ensuring it stays on one line.overflow: hidden: Hides any text that overflows the container.text-overflow: ellipsis: Displays an ellipsis (…) at the end of the truncated text.
Additional Notes:
- Browser Compatibility: While widely supported, there might be minor differences in behavior across different browsers.
- Custom Text Overflow: Instead of an ellipsis, you can specify a custom string using the
text-overflowproperty. For example:text-overflow: '... Read more'. - Responsive Design: Consider using media queries to adjust the
text-overflowbehavior based on screen size. - Accessibility: Be mindful of accessibility implications. Ensure that truncated content is accessible through other means, such as tooltips or expanding elements.
Example with custom text overflow:
.custom-overflow {
white-space: nowrap;
overflow: hidden;
text-overflow: '... See more';
}
By following these guidelines and combining the properties effectively, you can create clean and visually appealing text truncation in your web designs.