How to truncate long texts using CSS (text-overflow)

Using a back-end language to cut long strings is not always the best solution. Consider that a variable amount of space (on desktop the space would be bigger; on mobile devices it would be smaller) needs to be filled with some text. PHP, Ruby etc. will be ignorant of the actual size of the space that will be filled with text, so we need something on the front-end. Of course, JavaScript comes to mind, but there is an (even) easier way.

Using a CSS property text-overflow it is possible to cut the text exactly where you need it, when you need it. Example:

<div class="cut-the-text">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
.cut-the-text {
    width: 100px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;

text-overflow is well supported by all recent web browsers, but even on ancient ones like Internet Explorer 6 the text that goes beyond the limit is at least hidden. Anyway, the result is this:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Just remember that beside text-overflow you have to specify the size of the box, no wrap for the text, and to hide whatever goes beyond the limit of the container.