Is there a way for me to establish a maximum word count for a paragraph?

When my paragraphs get lengthy, I only want the first 30 words to display on two lines. Is there a way to achieve this using HTML, CSS, or JS? The code snippet I tried did not work as expected.

.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>

Answer №1

To achieve this effect, CSS alone is not enough. JavaScript must be implemented. The following code snippet will truncate a paragraph to 30 words and add ellipsis at the end. (This code splits the text into words using spaces.)

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>

Answer №3

CSS

When it comes to constraining text within specific parameters, there are some creative techniques you can employ:

  • The maximum width should not exceed 80 characters
  • Limited to just 2 lines of text
  • The total word count should be around 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

Achieving the goal of displaying only 30 words or maximum 2 lines requires careful scripting:

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>

Answer №4

Hey there! Below is a neat example in JS that could help solve your issue:

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;

//Merge each word
for (var i = 0; i < parts.length; i++) {
 //Loop and execute actions only on the first 2 lines
 if(count<2){
  outStr += ' ' + parts[i];
  
  //every fifteenth word, introduce a new-line
  if ((i + 1) % 15 === 0) {
    count ++;
    //Avoid new-line on the second row
    if(count!=2){
     outStr += "\n";
    }
  }
 }
}
//add ellipsis at the end of the string
console.log(outStr+'...');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

prepend a string to the start of ng-model

I am looking to enhance my ng-model variable by adding a specific string to it. This ng-model is being used for filtering data, specifically for elements that begin with the term "template". By adding this string to the ng-model, I hope to improve my searc ...

What could be causing the alignment issue with this html photo gallery?

Struggling to center a photo library on my webpage is really frustrating me. Does anyone have any tips? I've experimented with different ways to center it in the code, but nothing seems to do the trick :/ HTML: <div style="display: inline-block; ...

Modify all the content within the DIV using Regex, while keeping the HTML tags intact

I am attempting to replace all the text inside a DIV, including within its children, without modifying any HTML tags. Specifically, I want to switch all instances of 'Hello' to 'Hi'. Thank you for your help. var changes = $('div ...

Tips for refreshing the appearance of a window in angular when it is resized

I have a chat feature integrated into my application. I am looking to dynamically resize an image within the chat window when the width of the window falls below a certain threshold. Is there a method available to modify the CSS style or class based on the ...

Mastering the use of SVG icons in Angular 4+: A comprehensive guide

I have an icon.svg file with a collection of icons that I would like to use in my app, similar to how we display material icons. Does anyone have any ideas on how to include the file in the app and use these icons? I've tried looking for solutions a ...

Chrome scrolling causing Webkit mask to shift position

I have successfully created a rounded Google map after much effort. Here is the link to the JSFiddle: http://jsfiddle.net/DZTvR/13/ However, I encountered an issue in Chrome where the mask remains static while scrolling, unlike other browsers like FF, Op ...

Which Javascript/Css/HTML frameworks and libraries would you suggest using together for optimal development?

Interested in revamping my web development process with cutting-edge libraries, but struggling to navigate the vast array of tools available. The challenge lies in finding a harmonious blend of various technologies that complement each other seamlessly. I& ...

PHP: Using conditional statements to adjust datetime formatting for CSS styling

My title may not make sense, as I am new to PHP. I'm trying to create a custom member tag for my forum that shows "X Years of Experience" with different colors based on the number of years. For example, red for under 6 months, blue for year one, yell ...

deactivate a vessel, causing all of its contents to be rendered inactive

Hi there, I am in search of a container that has the ability to disable all elements within it, not just inputs but also images and other elements without the disabled property. I do not want to hide the container, but rather disable it. Do you know if suc ...

Customizing styles in ZK based on theme

I am currently working on a ZK application that has been styled using CSS, specifically the colors from the Sapphire theme. My goal is to have environment-dependent themes - Sapphire for production and Breeze for stage. While I have successfully implemente ...

Is Flex still wrapping elements even when set to nowrap?

My goal is to create a layout with 4 blocks, where the first section contains 2 blocks each occupying 50% of the width, followed by 2 other blocks in the next section. I am utilizing the flex property for this layout. I want the flex-container to take up ...

React component is unable to identify prop

I'm attempting to send an array of objects from the main App.js file to a smaller component using props. However, for some reason, the prop is not being recognized within the smaller component file. https://i.stack.imgur.com/WuyFr.png https://i.stac ...

confirmation message upon completing a form submission

<script> var remainingCredit = document.getElementById("cor_credit"); var remaining = document.getElementById("remain_credit"); function validateForm() { if (remaining.value < remainingCredit.value) { return conf ...

Having trouble displaying an image using output buffering in PHP and HTML, only to end up with a broken image

I've been working on a script that combines two PNG images - one as a watermark and the other as the source image. The idea is to blend these images together using the imagecopy function and display the result in the browser. However, despite my effor ...

Is it possible to obtain the index of a table row using querySelector?

Is it possible to find the rowIndex of the first occurrence of a table row within the #myTable using JavaScript? http://jsfiddle.net/bobbyrne01/fmj6np6m/1/ html .. <table id="otherTable"></table> <table id="myTable"></table> js ...

Extracting information from a checkbox list displayed within an HTML table

I have a table with multiple rows and two columns in each row. The first column contains text, and the second column consists of checkboxes. While I was able to retrieve the values from the first column, I am struggling to fetch the values of the selected ...

Guide to making a vertical clickable separator/line using bootstrap

Seeking advice on creating a layout where the left side consists of a sidebar menu occupying 24% and the right side contains main content taking up 75%, with a clickable vertical divider at 1% between them. When this line is clicked, the left part will hid ...

Transform the text upon hovering over the image, with the text positioned separate from the image

I'm looking for a solution where hovering over images in a grid area will change the text on the left side of the screen to display a predefined description of that image. I've been working on this problem for hours and would appreciate any help. ...

Transparent background with opaque text

I noticed that my div has a gray background with some opacity. <div className="absolute w-full h-full top-0 left-0 right-0 bottom-0 bg-slate-500 opacity-50 z-10"> <p className="relative top-1/2 px-8 text-center hea ...

Access a webpage whose URL has been dynamically assigned using JavaScript

I have a website that consists of a single page and features four tabs. Whenever a tab is clicked, it displays the corresponding content in a div while hiding the other three divs along with their respective content. To ensure a smooth user experience, I u ...