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

Incorporate ng-model to manage dynamically generated HTML elements

I have created dynamic div elements with a button inside, and I want to access its value using ng-model, but the value is not being retrieved. Here is my code: var url = "/api/chatBot/chatBot"; $http.post(url,data) .success(function(data){ $scope.mes ...

Bootstrap requires Visual Studio Code live-server plugin to function properly

I have been utilizing the Visual Studio Code IDE for my coding projects, along with a helpful plugin called "live server" that allows for quick checks of code changes. Everything was running smoothly with Bootstrap until I encountered an issue. When I att ...

Is an audio player/playlist necessary for showcasing a mix engineer's skills in their

As a newcomer to the world of web development with some background knowledge from school, I work as a mix engineer and have created a portfolio website. Previously, I utilized Soundcloud and Spotify's API to showcase my mixes/songs, but the external J ...

Ways to showcase numerous products within a single category label

views.py : def get_meals(request): template = loader.get_template('café/meals.html') meal_data = MealInfo.objects.all() category_data = MealsCategory.objects.all() context = { 'meals': meal_data, ' ...

What is the best way to align two HTML elements in a single column?

I need to adjust the layout of an existing <td> in order to display a checkbox and one additional field on the same line. The current setup places these elements on separate lines. Below is the provided HTML code: <!DOCTYPE html> <html> ...

What's the easiest method for moving div content from side to side?

Working on a plugin for WordPress, I am faced with the task of moving content in a slider from left to right and right to left. My current attempt is as follows: var effect = 'slide'; // Set the options for the chosen effect type var opti ...

YouTube videos cannot be embedded using an iframe on Firefox

I inserted a YouTube iframe code inside a div element. <div id="box"> <iframe width="300" height="315" src="//www.youtube.com/embed/82fn4mcNGJY" frameborder="0" allowfullscreen></iframe> </div> After applying CSS to sc ...

Utilizing CSS to Rearrange Columns Depending on Screen Size

Check out the progress on this page: If you scroll to the bottom, you'll find a list of links - displayed in 4 columns in the regular view. When you resize the screen, they shift into a single column. I want them to show as a single column on an iPh ...

Having trouble getting my local website to load the CSS stylesheet through Express and Node.js in my browser

https://i.stack.imgur.com/qpsQI.png https://i.stack.imgur.com/l3wAJ.png Here is the app.js screenshot: https://i.stack.imgur.com/l3wAJ.png I have experimented with different combinations of href and express.static(""); addresses. However, I am ...

Modifying the Vue.js Vue3-slider component for custom color schemes

Currently, I am using the vue-slider component and would like to customize the color of the slider itself. The specific class that needs to be styled is "vue-slider-dot-tooltip-inner". Below is a screenshot displaying the original CSS styling for vue-slid ...

Learn the art of perfectly aligning text in bootstrap 5

I am looking to align text in the same way shown in this image from Libre Office. Libra Office: https://i.sstatic.net/1dvVx.png This is how the webpage appears: https://i.sstatic.net/JnFSP.png Is there a way to make the webpage resemble the formatting i ...

What is the best way to seamlessly integrate an image icon into a sentence, so it appears as a natural part of the text

I'm struggling to insert an (i) information icon before the phrase "Learn more" in the sentence: "Click on the 'Learn more' buttons for additional information." The icon keeps overlapping with the words "Learn more." Could someone provide s ...

Is it possible to adjust the size of a p5.js canvas within a bootstrap Div container?

I am attempting to incorporate a p5js canvas into a bootstrap grid structure. My goal is to have each div within the grid contain its own unique p5js canvas, which should adjust in size when the browser is resized. Below is my bootstrap grid setup, showca ...

The implementation of modal pop-ups is resulting in unresponsive touch areas on mobile devices and tablets

I recently finished putting together a one-page website using Twitter Bootstrap, based on a theme from Themeforest that I heavily customized. However, when viewing the site on a mobile or tablet, I noticed an issue where the top 2/3 of the page is unrespon ...

Generate a two-dimensional array of pixel images using HTML5 canvas

Hey everyone, I'm trying to copy an image pixel to a matrix in JavaScript so I can use it later. Can someone take a look and let me know if I'm using the matrix correctly? I'm new to coding so any help is appreciated. Thanks! <canvas id= ...

Display the final row by hovering over the line

<table> <thead> <tr> <th>First</th> <th>Second</th> <th></th> </tr> </thead> <tbody> <tr> <td>Data1</td> <td>Dat ...

Safari does not stop the scrolling of the <body style="overflow-y: hidden"> tag

Welcome to this simple HTML page <body style="overflow-y: hidden"> ... </body> This page is designed to prevent scrolling by using the CSS property overflow-y: hidden. While this functionality works as intended on most browsers, it does ...

What is the best way to invoke the datepicker function on all rows of table data that share the 'datepicker' class?

Hey there! I'm working with a table that features a JavaScript function for a datepicker, as well as the ability to add and delete rows. The challenge I'm facing is that each new row created has the same ID as the previous one. How can I ensure t ...

Position Bootstrap 5 modal footer elements to the left and right for an enhanced visual

Can anyone assist me with customizing the Bootstrap 5 modal footer? I am looking to align a text (either using span or label) to the left and a button to the right within the modal footer. I came across this solution and attempted to implement it by cha ...

The scrolling behavior varies in Firefox when using the mouse wheel

Currently, I am working on a website where I want to display large text on the screen and have the ability to scroll two divs simultaneously. This functionality is already in place. I can scroll the divs, but I'm facing an issue with the jumps being t ...