How to Truncate Text with Ellipsis in CSS: Simple Guide
To truncate text with an ellipsis in CSS, use the combination of
overflow: hidden;, white-space: nowrap;, and text-overflow: ellipsis; on a container with a fixed width. This hides overflowed text and shows three dots to indicate more content.Syntax
Use these CSS properties together to truncate text with ellipsis:
overflow: hidden;hides any text that goes outside the container.white-space: nowrap;prevents the text from wrapping to the next line.text-overflow: ellipsis;adds the three dots (...) at the end of truncated text.- A fixed
widthormax-widthis required to define the truncation boundary.
css
.truncate {
width: 200px;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}Example
This example shows a paragraph with long text truncated with an ellipsis when it exceeds the container width.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Text Truncate with Ellipsis</title> <style> .truncate { width: 250px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; border: 1px solid #ccc; padding: 8px; font-family: Arial, sans-serif; } </style> </head> <body> <p class="truncate">This is a very long text that will not fit inside the container and will be truncated with an ellipsis.</p> </body> </html>
Output
A single-line paragraph inside a 250px wide box showing truncated text ending with three dots (...)
Common Pitfalls
Common mistakes when using ellipsis truncation include:
- Not setting a fixed
widthormax-width, so the container expands and no truncation happens. - Forgetting
white-space: nowrap;, which causes text to wrap and ellipsis not to appear. - Using ellipsis on multi-line text without special handling (ellipsis works only on single-line by default).
css
/* Wrong way: missing width and nowrap */ .truncate-wrong { overflow: hidden; text-overflow: ellipsis; } /* Right way: includes width and nowrap */ .truncate-right { width: 200px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
Quick Reference
Summary tips for truncating text with ellipsis:
- Always set a fixed
widthormax-width. - Use
white-space: nowrap;to keep text on one line. - Apply
overflow: hidden;to hide overflowed text. - Use
text-overflow: ellipsis;to show the three dots. - For multi-line truncation, consider advanced CSS or JavaScript solutions.
Key Takeaways
Use overflow: hidden, white-space: nowrap, and text-overflow: ellipsis together to truncate text with ellipsis.
A fixed width or max-width is required for truncation to work.
Ellipsis truncation works only on single-line text by default.
Without white-space: nowrap, text will wrap and ellipsis won't appear.
For multi-line truncation, additional techniques are needed beyond basic CSS.