Truncate multiline text with an ellipsis
We have been using CSS property text-overflow: ellipsis
to truncate the text with an ellipsis (…). But, it works only on a single line of text.
We can use -webkit-line-clamp
to truncate multiline text. Don’t get concerned with the -webkit
vendor prefix. Trust me, this works on modern browsers. We need to set three more properties to make it work:
- The
display
property must be set to-webkit-box
or-webkit-inline-box
. - Use
-webkit-line-clamp
to specify the number of lines to clamp, example:-webkit-line-clamp: 3;
- The
-webkit-box-orient
property must be set tovertical
. - Then, set
overflow
tohidden
, otherwise, you’ll see ellipsis with overflowing text in some browsers.
CSS
.clamp-lines {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 3; /* Number of lines to show */
overflow: hidden;
}
/* Presentational styles */
.card {
padding: 1em;
border-radius: 0.25em;
background-color: #4f46e5;
color: #eef2ff;
}
HTML
<div class="card">
<p class="clamp-lines">
In the morning when thou findest thyself unwilling to rise, consider with
thyself presently, it is to go about a man's work that I am stirred up. Am I
then yet unwilling to go about that, for which I myself was born and brought
forth into this world? Or was I made for this, to lay me down, and make much
of myself in a warm bed? 'O but this is pleasing.' And was it then for this
that thou wert born, that thou mightest enjoy pleasure? Was it not in very
truth for this, that thou mightest always be busy and in action? Seest thou
not how all things in the world besides, how every tree md plant, how
sparrows and ants, spiders and bees: how all in their kind are intent as it
were orderly to perform whatsoever (towards the preservation of this orderly
universe) naturally doth become and belong unto thin? And wilt not thou do
that, which belongs unto a man to do? Wilt not thou run to do that, which
thy nature doth require?
</p>
</div>
Preview
In the morning when thou findest thyself unwilling to rise, consider with thyself presently, it is to go about a man's work that I am stirred up. Am I then yet unwilling to go about that, for which I myself was born and brought forth into this world? Or was I made for this, to lay me down, and make much of myself in a warm bed? 'O but this is pleasing.' And was it then for this that thou wert born, that thou mightest enjoy pleasure? Was it not in very truth for this, that thou mightest always be busy and in action? Seest thou not how all things in the world besides, how every tree md plant, how sparrows and ants, spiders and bees: how all in their kind are intent as it were orderly to perform whatsoever (towards the preservation of this orderly universe) naturally doth become and belong unto thin? And wilt not thou do that, which belongs unto a man to do? Wilt not thou run to do that, which thy nature doth require?