CSS: long string management (ellipsis)

October 20, 2013

Last update: March 28, 2020

The problem

Sooner or later, as frontenders, we have to fight against long strings that don't fit the box in which we put them. The best solution are ellipses, but how to calculate where and when put them?

A solution

Keep calm, no complex JavaScript or others strange techniques are required to have a great result. Just few CSS properties and we can forget the problem.

Below an example:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="utf-8"/>
    <title>Ellipsis</title>
    <style>
    .string {
        display: inline-block; /* or block */
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        width: 5em;
    }
    </style>
</head>
<body>
    <span class="string">very very very long string</span>
</body>
</html>

Bear in mind that the container must be a block-level or inline-block element, so the solution above does not work with inline elements. In addition, it is a good thing if we offer to the user the possibility to read the entire string: an easy way is to use the title attribute.

References

  1. text-overflow on MDN


A photo of Elia Contini
Written by
Elia Contini
Sardinian UX engineer and a Front-end web architect based in Ticino, Switzerland. Marathoner, traveller, wannabe nature photographer.