Truncating and displaying long text using CSS

1 Min. Read
Aug 21, 2019

Truncating the long text is usually common in the website as it helps to keep the layout clean and spacious. There are various methods used to truncate the long text, however the one which we will be discussing upon is using the CSS property.Here is the line of code which truncates the line of text :

1
2
3
4
5
6
  .read-less {
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 5;
  -webkit-box-orient: vertical;
}

In above code, overflow property specifies what to do if the content specified in certain element gets too large to fit in. And hidden hides the overflowed content. WebKit is a layout engine designed to allow web browsers to render web pages. -webkit-box will be replaced by the standard box and you won’t need multiple rules for the same thing for multiple browsers. webkit-line-clamp specify from which line should truncation be applied.-webkit-box-orient defines how the element should lay out it’s content i.e vertically or horizontally.

We can apply this css class to certain element in HTML code using javascript. All we need is to select the html element in event handling and apply the above css class to that particular element.For e.g

1
2
3
4
5
6
7
8
9
10
$('.btn-read-more').click(function(){
    $(this).parents('article').find('h5').toggleClass('read-less');
    $(this).parents('article').find('p').toggleClass('read-less');
    $(this).parents('article').find('p').toggleClass('scroll');
    if( $(this).text() == 'Read More'){
        $(this).text('Read Less');
    }else{
        $(this).text('Read More');
    }
});

Here, after the click event on the button having the class name .btn-read-more, it traverse to it’s parent which is article and within that class finds the p tag to which the read-less class is applied. As a result, the text inside that element gets truncated/clamp showing the content upto line upto count of 5.The custom CSS class ‘scroll’ defines the particular height for the content display and gives the scroll functionality for the overflow content.During this the text within the button is changed from ‘Read More’ to ‘Read Less’.