Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit text length to n lines using CSS

People also ask

How do I limit text lines in CSS?

If you want to limit the text length to one line, you can clip the line, display an ellipsis or a custom string. All these can be done with the CSS text-overflow property, which determines how the overflowed content must be signalled to the user.


There's a way to do it using unofficial line-clamp syntax, and starting with Firefox 68 it works in all major browsers.

body {
   margin: 20px;
}

.text {
   overflow: hidden;
   text-overflow: ellipsis;
   display: -webkit-box;
   -webkit-line-clamp: 2; /* number of lines to show */
           line-clamp: 2; 
   -webkit-box-orient: vertical;
}
<div class="text">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam consectetur venenatis blandit. Praesent vehicula, libero non pretium vulputate, lacus arcu facilisis lectus, sed feugiat tellus nulla eu dolor. Nulla porta bibendum lectus quis euismod. Aliquam volutpat ultricies porttitor. Cras risus nisi, accumsan vel cursus ut, sollicitudin vitae dolor. Fusce scelerisque eleifend lectus in bibendum. Suspendisse lacinia egestas felis a volutpat.
</div>

Unless you care about IE users, there is no need to do line-height and max-height fallbacks.


What you can do is the following:

.max-lines {
  display: block;/* or inline-block */
  text-overflow: ellipsis;
  word-wrap: break-word;
  overflow: hidden;
  max-height: 3.6em;
  line-height: 1.8em;
}
<p class="max-lines">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc vitae leo dapibus, accumsan lorem eleifend, pharetra quam. Quisque vestibulum commodo justo, eleifend mollis enim blandit eu. Aenean hendrerit nisl et elit maximus finibus. Suspendisse scelerisque consectetur nisl mollis scelerisque.</p>

where max-height: = line-height: × <number-of-lines> in em.


Working Cross-browser Solution

This problem has been plaguing us all for years.

To help in all cases, I have laid out the CSS only approach, and a jQuery approach in case the css caveats are a problem.

Here's a CSS only solution I came up with that works in all circumstances, with a few minor caveats.

The basics are simple, it hides the overflow of the span, and sets the max height based on the line height as suggested by Eugene Xa.

Then there is a pseudo class after the containing div that places the ellipsis nicely.

Caveats

This solution will always place the ellipsis, regardless if there is need for it.

If the last line ends with an ending sentence, you will end up with four dots....

You will need to be happy with justified text alignment.

The ellipsis will be to the right of the text, which can look sloppy.

Code + Snippet

jsfiddle

.text {
  position: relative;
  font-size: 14px;
  color: black;
  width: 250px; /* Could be anything you like. */
}

.text-concat {
  position: relative;
  display: inline-block;
  word-wrap: break-word;
  overflow: hidden;
  max-height: 3.6em; /* (Number of lines you want visible) * (line-height) */
  line-height: 1.2em;
  text-align:justify;
}

.text.ellipsis::after {
  content: "...";
  position: absolute;
  right: -12px; 
  bottom: 4px;
}

/* Right and bottom for the psudo class are px based on various factors, font-size etc... Tweak for your own needs. */
<div class="text ellipsis">
  <span class="text-concat">
Lorem ipsum dolor sit amet, nibh eleifend cu his, porro fugit mandamus no mea. Sit tale facete voluptatum ea, ad sumo altera scripta per, eius ullum feugait id duo. At nominavi pericula persecuti ius, sea at sonet tincidunt, cu posse facilisis eos. Aliquid philosophia contentiones id eos, per cu atqui option disputationi, no vis nobis vidisse. Eu has mentitum conclusionemque, primis deterruisset est in.

Virtute feugait ei vim. Commune honestatis accommodare pri ex. Ut est civibus accusam, pro principes conceptam ei, et duo case veniam. Partiendo concludaturque at duo. Ei eirmod verear consequuntur pri. Esse malis facilisis ex vix, cu hinc suavitate scriptorem pri.
  </span>
</div>

jQuery Approach

In my opinion this is the best solution, but not everyone can use JS. Basically, the jQuery will check any .text element, and if there are more chars than the preset max var, it will cut the rest off and add an ellipsis.

There are no caveats to this approach, however this code example is meant only to demonstrate the basic idea - I wouldn't use this in production without improving on it for a two reasons:

1) It will rewrite the inner html of .text elems. whether needed or not. 2) It does no test to check that the inner html has no nested elems - so you are relying a lot on the author to use the .text correctly.

Edited

Thanks for the catch @markzzz

Code & Snippet

jsfiddle

setTimeout(function()
{
	var max = 200;
  var tot, str;
  $('.text').each(function() {
  	str = String($(this).html());
  	tot = str.length;
    str = (tot <= max)
    	? str
      : str.substring(0,(max + 1))+"...";
    $(this).html(str);
  });
},500); // Delayed for example only.
.text {
  position: relative;
  font-size: 14px;
  color: black;
  font-family: sans-serif;
  width: 250px; /* Could be anything you like. */
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="text">
Old men tend to forget what thought was like in their youth; they forget the quickness of the mental jump, the daring of the youthful intuition, the agility of the fresh insight. They become accustomed to the more plodding varieties of reason, and because this is more than made up by the accumulation of experience, old men think themselves wiser than the young.
</p>

<p class="text">
Old men tend to forget what thought was like in their youth;
</p>
 <!-- Working Cross-browser Solution

This is a jQuery approach to limiting a body of text to n words, and end with an ellipsis -->

As far as I can see, this would be possible only using height: (some em value); overflow: hidden and even then it wouldn't have the fancy ... at the end.

If that is not an option, I think it's impossible without some server side pre-processing (difficult because text flow is impossible to predict reliably) or jQuery (possible but probably complicated).