1

Some of my paragraphs have a very long description, and I only want, say, the first 30 words to be written in two lines.

How can this be achieved in HTML, CSS, or JS? I tried with the code below but it's not for word and this show me in one line.

.long-text{
  width: 70ch;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
<p class ="long-text">In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before the final copy is </p>
Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51
Mazdak
  • 15
  • 2
  • 9
  • https://stackoverflow.com/questions/47761085/how-can-i-set-a-character-limit-for-paragraph – Carles Arteche Rodríguez Mar 24 '22 at 10:45
  • @CarlesArtecheRodríguez He/She is asking for setting limits according to words, not characters. Pls read the question properly before answering – Archit Gargi Mar 24 '22 at 10:48
  • I don't understand what you mean by displaying them in 2 lines... Do you mean that you want 15 words to be in 1 line and the other 15 in 2nd and the rest of them hidden? – Archit Gargi Mar 24 '22 at 10:49
  • this is not the solution you asked for and it depend upon where you are using description but you can add view description button . Add onclick event on that button and show description in a modal or popup. – rootShiv Mar 24 '22 at 10:56

4 Answers4

2

This cannot be achieved using CSS. You need to use JS for this. The below code will limit the paragraph to 30 words only and add "..." in the end. (This code gets words by splitting the text in a paragraph by space.)

var para = document.getElementsByClassName("long-text")[0];
var text = para.innerHTML;
para.innerHTML = "";
var words = text.split(" ");
for (i = 0; i < 30; i++) {
  para.innerHTML += words[i] + " ";
}
para.innerHTML += "...";
<p class="long-text">In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used as a placeholder before the final copy is </p>
Archit Gargi
  • 634
  • 1
  • 8
  • 24
  • why is this code available only in the first article?! how can I fix it! – Mazdak Mar 24 '22 at 12:47
  • I want to show in all of the articles! What can I do? – Mazdak Mar 24 '22 at 12:51
  • 1
    @Mazdak well u have to apply that js code to each and every para. You can give those paras a class and then use a loop to apply it. – Archit Gargi Mar 24 '22 at 14:09
  • I'm no "JS Guru", ah-ah...!, but doing a `for` Loop is not very *efficient* in my Opinion, the Execution would probably take about 10 Sec (oops...!) if @OP wanted to keep the first 1000 Words instead of only 30 (=0.3 Sec). More efficient would be for example: `para.innerHTML = text.split(" ",30).join(" ") + " ...";` which does "the job" in 1 Line in about 0.2 Sec for any Length/Number of Words... :idea: – chivracq Apr 29 '22 at 12:00
  • @chivracq I did not dive very deep into JavaScript and hence don't know that these functions exist. – Archit Gargi Apr 29 '22 at 12:04
  • Yeah, well, you used `split()`, then you know what it does and its Syntax..., and `join()` does the "Contrary" of `split()`... – chivracq Apr 29 '22 at 12:07
  • @chivracq I did not know that there is a `join()` function and hence didn't use it. It may not be efficient and hence not be usable in every situation but it works in this one, so why change the code? – Archit Gargi Apr 29 '22 at 12:08
  • No "need" to "change the Code", I just mentioned a "Limitation"... (Maybe I'll post a separate Answer even if I like your Implementation...) And well, we all learn everyday, which is good, ah-ah...! (Hum, and `split()` and `join()` are btw not "*Functions*" but "*Methods*", in JS-Terminology... :wink:) // If you are interested, "[easy Site](https://www.tutorialspoint.com/javascript/javascript_arrays_object.htm)" I use myself about (basic) JavaScript Functionality... – chivracq Apr 29 '22 at 12:22
0
.long-text {
  inline-size: 150px;
  overflow-wrap: break-word;
}

Source: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Text/Wrapping_Text

Should work, but I am unable to test right now.

codingmaster398
  • 249
  • 4
  • 14
0

CSS

you cannot limit words, but you may do some hacking math, where:

  • max width would be 80 characters
  • max 2 lines of text
  • in total should give you about 30 words

.container {
  max-width: 80ch;
  padding: 20px;
  border: 1px solid #fed;
}

.container p {
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
<div class="container">
  <p>Aenean vulputate libero a purus posuere, eget rhoncus risus iaculis. Aenean non turpis diam. Ut pretium sagittis porttitor. Curabitur placerat interdum lobortis. Aliquam non laoreet risus. Donec eget ornare nunc. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam sed sapien augue. Suspendisse pharetra venenatis nunc. Maecenas interdum placerat felis vitae fringilla. Pellentesque a mollis justo.</p>
</div>

JS

Displaying only 30 words, or 2 lines max.

var string = "Aenean vulputate libero a purus posuere, eget rhoncus risus iaculis. Aenean non turpis diam. Ut pretium sagittis porttitor. Curabitur placerat interdum lobortis. Aliquam non laoreet risus. Donec eget ornare nunc. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Aliquam sed sapien augue. Suspendisse pharetra venenatis nunc. Maecenas interdum placerat felis vitae fringilla. Pellentesque a mollis justo."

var exploded = string.split(" ")


document.getElementById("target").innerHTML =exploded.slice(30).join(" ")
div{
border:1px solid #fed;
padding:5px;
}

p{
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
<div><p id="target"></p></div>
Unamata Sanatarai
  • 6,475
  • 3
  • 29
  • 51
  • But that's not a reliable method, right? – Archit Gargi Mar 24 '22 at 10:50
  • not reliable in terms of exact word-count. but remember, a more reliable measure is characters, as they can be counted, words may be all 2 letters long, or 10 letters long. – Unamata Sanatarai Mar 24 '22 at 10:51
  • But he/she is asking on basis of words, right? – Archit Gargi Mar 24 '22 at 10:52
  • I would think `slice(30)` is not correct actually, => should be `slice(0,30)`, at least in "my" Browsers, unless `slice()` *now* behaves differently in "later" FF Versions and/or other Browsers... // (Tested in [iMacros for FF v8.8.2 + PM v26.3.3] + [iMacros for FF v8.9.7 + FF v55.0.5].) – chivracq Apr 27 '22 at 19:35
0

Hello this JS example should be a fine resolution for your problem:

var str = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum',
parts = str.split(' '),
outStr = '';
count = 0;

//Combine each word
for (var i = 0; i < parts.length; i++) {
 //cicle and do things only on the first 2 lines
 if(count<2){
  outStr += ' ' + parts[i];
  
  //every fifteenth word, add a new-line
  if ((i + 1) % 15 === 0) {
    count ++;
    //on the second row avoid new-line
    if(count!=2){
     outStr += "\n";
    }
  }
 }
}
//add 3 points at the end of the string
console.log(outStr+'...');
Sid Biffi
  • 522
  • 7
  • 16