If you have an unbreakable string such as a long sentence without any spaces, by default it will overlap the container. Have a look at the below paragraph -.
<div class="text-container">
Loremipsumdolorsitamet,consecteturadipiscingelitseddoeiusmodtemporincididuntutlaboreetdoloremagnaaliquaUtenimadminimveniam
</div
This will be overflowing the parent container like this –
To handle such cases, we will use overflow:hidden
& word-wrap: break-word
which will help unbroken string to wrap and break onto new lines, fitting within the container.
.text-container {
width: 300px;
word-wrap: break-word;
overflow-wrap: break-word;
white-space: normal;
overflow: hidden;
border: 1px solid #ccc;
padding: 10px;
}
In the above CSS, the white-space:
normal
property ensures that the text behaves normally by wrapping onto new lines when needed, instead of staying on one long line. word-wrap: break-word
allows long, unbroken text strings to break and wrap onto the next line.
After adding the CSS, the output will be –
To cut off overflowing text and display an ellipsis (...
), you can use the text-overflow
property. This is useful in situations where you want to limit the text shown while indicating that more text is hidden.
.text-container {
width: 300px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
border: 1px solid #ccc;
padding: 10px;
}
white-space: nowrap
prevents the text from wrapping to the next line. This keeps the text on a single line, even if it overflows. overflow: hidden
: ensures that any text that goes beyond the container’s width is hidden. text-overflow: ellipsis
: displays an ellipsis (...
) at the end of the visible text, indicating that there is more text beyond what’s shown.