Truncate String with CSS

May 18, 2022
2 min read
329 words

In this article, I am going to cover how you can create truncate strings or paragraphs by just using CSS.

What is Truncate?

Truncate means to make something shorter, especially by cutting off the top or end. In paragraphs, we make the string shorter by cutting the lines.

Lorem Ipsum is simply a dummy text of the printing and typesetting industry. Lorem 
Ipsum has been the industry's standard dummy text ever since the 1500s when an 
unknown printer took a galley of type and scrambled it to make a type specimen book. 
It has survived not only five centuries, but also the leap into electronic typesetting.

The above paragraph contains 4 lines and we want to make it short to two lines. like this -

Lorem Ipsum is simply a dummy text of the printing and typesetting industry. Lorem 
Ipsum has been the industry's standard dummy text ever since the 1500s, when....

How to use it?

First, let's take a look at how my HTML is looking-

HTML

index.html

<div class="container">
  <h3>Truncate-2 (two line)</h3>
  <p class="truncate-2">
    Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer
    took a galley of type and scrambled it to make a type specimen book. It has survived not only five 
    centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was 
    popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and 
    more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
  </p>
</div>

So as you can see I've applied the truncate-1 class to the paragraph. This class contains the following properties-

CSS

styles.css

.truncate-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;    /* Change the number as per your requirement */
  -webkit-box-orient: vertical;
  overflow: hidden;
}

Result

After that result is something like this- truncate-1

Jatin's Newsletter

I write monthly Tech, Web Development and chrome extension that will improve your productivity. Trust me, I won't spam you.

Share on Social Media: