What is the best way to ensure that text only displays up to five lines and fully collapses using CSS or javascript/jquery?

Hello everyone, I have come across an issue. English is not my strong suit, but I will do my best to explain it thoroughly.

The problem at hand is a design requirement in the draft that specifies showing up to five lines of text. If the text exceeds this limit, a button should appear to expand and show more text! I am not very well-versed in JavaScript and know only a little bit about it. I was wondering if this effect can be achieved using CSS alone?

If you have any knowledge on how to implement this using JavaScript, please feel free to share it with me~ Thank you in advance for your assistance, as I am clueless about how to proceed. Thank you.

.content {
  height: 110px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 5;
}

.more {
  text-align: center;
}
.more a {
  text-decoration: none;
  color: #222;
}
<div class="demo">
  <p class="content">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Suscipit odit fugit debitis, quibusdam esse eius ullam odio cupiditate cumque nostrum asperiores libero, sapiente aliquid animi? Saepe eligendi doloremque possimus. Velit sunt earum aliquam debitis quos eum atque nemo eius, hic quas doloremque facere et voluptatibus voluptatum eaque corrupti impedit ipsum beatae incidunt sapiente aliquid animi? Saepe eligendi doloremque possimus. Velit sunt earum aliquam debitis quos eum atque nemo eius, hic quas doloremque facere et voluptatibus voluptatum eaque corrupti impedit ipsum beatae incidunt sapiente aliquid animi? Saepe eligendi doloremque possimus. Velit sunt earum aliquam debitis quos eum atque nemo eius, hic quas doloremque facere et voluptatibus voluptatum eaque corrupti impedit ipsum beatae incidunt 
  </p>
  
  <div class="more">
    <a href="javaScript:;" class="show">V</a>
  </div>
</div>

https://i.sstatic.net/j6w9r.png

Answer №1

If you're looking to achieve this using jQuery, here's a possible solution:

$('.read-more').click(function(){
  $(this).remove(); // remove read more button
  $('.content').addClass('expanded'); // add the expanded class to the content section when read more button is clicked
});
.content {
  height: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 4;
}
.content.expanded{
  height:auto;
  overflow:visible;
  text-overflow: none
}
.read-more {
  text-align: center;
}
.read-more a {
  text-decoration: none;
  color: #333;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="post">
  <p class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla et eros ac lorem eleifend mattis. Mauris quis libero nibh. Vestibulum erat sem, placerat in velit aliquet, congue pulvinar arcu. Ut at ultricies est. Proin elementum risus nec bibendum efficitur. Sed vitae molestie metus. Cras eget tempus ligula. Suspendisse ultricies nunc tristique turpis accumsan, quis faucibus sapien tempus. Phasellus nec tortor leo.
  </p>
  
  <div class="read-more">
    <a href="#" class="show">Read More</a>
  </div>
</div>

Answer №2

Here is a sample showcasing pure css styling.

* {
  box-sizing: border-box;
}

body {
  background-color: #646464;
  color: #fff;
}

header {
  background-color: rgba(0, 0, 0, 0.5);
  font-size: 1.5em;
  text-align: center;
  padding: 1em;
}

.panel-wrapper {
  position: relative;
}

.btn {
  color: #fff;
  background: #000;
  border-radius: 1.5em;
  left: 30%;
  padding: 1em;
  text-decoration: none;
  width: 40%;
}

.show, .hide {
  position: absolute;
  bottom: -1em;
  z-index: 100;
  text-align: center;
}

.hide {
  display: none;
}

.show:target {
  display: none;
}

.show:target ~ .hide {
  display: block;
}

.show:target ~ .panel {
  max-height: 2000px;
}

.show:target ~ .fade {
  margin-top: 0;
}

.panel {
  position: relative;
  margin: 2em auto;
  width: 70%;
  max-height: 100px;
  overflow: hidden;
  transition: max-height 0.5s ease;
}

.fade {
  background: linear-gradient(to bottom, rgba(100, 100, 100, 0) 0%, #646464 75%);
  height: 100px;
  margin-top: -100px;
  position: relative;
}
<header>CSS Only: Show More</header>
<div class="panel-wrapper">
  <a href="#show" class="show btn" id="show">Show Full Article</a> 
  <a href="#hide" class="hide btn" id="hide">Hide Full Article</a> 
  <div class="panel">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit...

And when this happens, and when we allow freedom ring, when we let it ring from every village and every hamlet, from every state and every city, we will be able to speed up that day when all of God's children, black men and white men, Jews and Gentiles, Protestants and Catholics, will be able to join hands and sing in the words of the old Negro spiritual:

                Free at last! Free at last!

                Thank God Almighty, we are free at last!
   
  </div><!-- end panel -->
  <div class="fade"></div>
</div><!-- end panel-wrapper -->

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

Is there a method to delay the loading of a webpage until an image has fully loaded (preloading)?

How can I ensure that an image used in a preloader is loaded before the other contents on my website? <div class="overlay" id="mainoverlay"> <div class="preloader" id="preloader"> <img src="images/logo128.png" id="logo-p ...

jquery selector targeting a select optiongroup that contains a specific label value

In my code, I have a select multiple with option groups: <select _ngcontent-oeq-14="" class="form-control" id="category-select" multiple=""> <optgroup label="grocery products"> <option>meat</option> <option>dai ...

Why do I keep getting undefined when I use React.useContext()?

I'm currently using Next.js and React, employing react hooks along with context to manage state within my application. Unfortunately, I've encountered a perplexing issue where React.useContext() is returning undefined even though I am certain tha ...

What is the best way to manage a situation where no link is returned to the "to" attribute of a Link component in React

Hey, I'm just starting out in programming and I have a question about handling the default case where no link is returned in the switch statement below: class ParentComponent extends React.PureComponent { get_link = () => { const item ...

Transform HTML content into a PDF document with page breaks

Currently, I am developing a function that involves an HTML template. The purpose of this function is to generate a dynamic template and convert it into a PDF. So far, I have been able to achieve this using the following code: var output = ''; ...

NodeJS Socket not transmitting file after connection with client

Having scoured the depths of various resources, including SO and Google, I have hit a roadblock. I am struggling to understand why the socket is failing to capture the uploaded file via the form; it simply stops after connecting. When I check the console, ...

Changing an object received as a prop in Vue.js

Is it acceptable to mutate values in a prop when passing an Object reference? In the process of developing a web application that involves passing numerous values to a component, I am exploring the most efficient method of handling value passing between c ...

Having trouble getting the Vue checkbox change event to work?

I am currently utilizing Vue to handle a function that is not triggering on the change event when a checkbox is checked. I am uncertain if the issue lies in the fact that I have placed it within the mounted lifecycle hook or if there is another underlying ...

A guide on reading an external JSON file using React

I'm trying to integrate an external JSON file into my React app. To demonstrate what I'm aiming for, I've provided a functional example on Codesandbox.io: https://codesandbox.io/s/morning-tdd-we2v3?file=/src/App.js Currently, the example ...

Displaying alerts and feedback - validating forms

I am relatively new to the world of web development and am eager to progress in the right direction. I have a question regarding form validation. I have a small form that is designed to input information into a database, requiring the use of PHP. Once the ...

Modify Javascript to exclusively focus on SVG paths

I successfully created an SVG animation using JSFiddle, but when I transferred the SVG to Shopify, the Javascript that animates the path stopped working. It seems like the issue is with the JavaScript targeting all paths on the page instead of just the sp ...

Using Font Color in Gmail HTML Emails

While working on styling an HTML email, I've encountered an unexpected issue with inline CSS in Gmail. I set the color of text in a table row using the following code: <tr style='color: #000; font-size: 14px; font-family: Verdana, serif;' ...

Perform individual conditions (filters) sequentially within a MongoDB query

Currently, I am working on a query that involves using $and to apply multiple filters or conditions. While explaining the query, I realized that $and does not function in the same way as the JavaScript && operator. How can I simulate JavaScript && functi ...

Tips for sending a property to a function that is imported and produces a component in React

I need help figuring out how to pass an argument back to my component library that is imported in a parent app as a dependency. The specific issue arises when I am trying to implement a brand concept in the theme object. The goal is to switch the theme bas ...

There was an issue encountered while trying to install Electron using the command 'npm install electron'

While attempting to install electron using npm install electron, I encountered the following error: 908 error code 1 909 error path C:\Users\name\Documents\name\Code\code\node_modules\gl 910 error command failed ... ...

Mobile Bootstrap 4 experiencing logo display issue

My .navbar logo disappears when the screen width is under 768px. I've seen a similar post about this issue, but they had set a very high height. I haven't specified a height for my navbar or navbar brand. Any help would be greatly appreciated, th ...

Tips for aligning divs side by side with smaller divs stacked below them

I have a collection of dynamically generated divs that act as panels for selecting different options. These divs can be categorized into two types: regular and short. The height of the regular divs is determined using JavaScript to match the height of the ...

Using the PUT method in combination with express and sequelize

I am having trouble using the PUT method to update data based on req.params.id. My approach involves retrieving data by id, displaying it in a table format, allowing users to make changes, and then updating the database with the new values. Here is the co ...

WordPress admin-ajax.php not receiving Ajax call

Trying to implement AJAX in a WordPress admin submenu to call a function, I encountered the following issue: jQuery('#deleteProj').submit(ajaxSubmit); function ajaxSubmit(){ var tobeDeleted = jQuery(this).serialize(); alert(tobeDeleted); ...

Exploring Zustand through Laravel validation errorsUnderstanding Zustand can be

I'm currently working on incorporating Zustand into my NextJS application. I have set up a Laravel endpoint for user login functionality. When there are validation errors, the endpoint sends back JSON in the following format: { "message" ...