Trimming text from the start and inserting ellipsis in a multi-line passage

My goal is to present a paragraph on the webpage that will be dynamically updated based on user actions. I want to restrict the content to a specified number of lines and if the user tries to exceed this limit, the beginning of the paragraph should be truncated with an ellipse as an indicator.

For example, with a maximum of 2 lines: Line number 1, Line2. If another line (line3) is added, it should display as: ...Line2. Line3.

I have experimented with different approaches, such as setting the display property to -webkit-box and utilizing the -webkit-line-clamp feature to limit the content to 4 lines.

p {
display: -webkit-box;
max-width: 200px;
-webkit-line-clamp: 4;
-webkit-box-orient: vertical;
overflow: hidden;}

However, I encountered challenges in positioning the ellipse at the beginning of the text and truncating from the start rather than the end. The limitation to 4 lines also posed a constraint.

.ellipsis {
overflow: hidden;
width: 60px;
position: relative
direction: rtl; 
margin-left: 15px;
white-space: nowrap;
}   
.ellipsis:after {
position: absolute;
left: 0px;
content: "...";
}

Due to using multiline text, the white-space property set to nowrap was not applicable. Despite browsing through related questions on Stack Overflow, the specific requirement for my scenario remained distinct.

References to similar inquiries:

- I need an overflow to truncate from the left, with ellipses

- Text-overflow ellipsis on the left side

- Applying an ellipsis to multiline text

Answer №1

This is a simple method to handle text overflow.

function adjustOverflow(el, content) {
  const container = el.parentElement;
  const words = content.split(' ');
  let index = 0;

  do {
    el.innerText = index ? `… ${words.slice(index).join(' ')}` : content;
  } while (container.scrollHeight > container.clientHeight && ++index < words.length);
}

const resizeObserver = new ResizeObserver(() => {
  adjustOverflow(document.getElementById('target'),
      'A few lines of text will overflow and run over, and the beginning will get chopped off.');  
});

resizeObserver.observe(document.getElementById('outer'));
#outer {
  width: 150px;
  height: 80px;
  overflow: hidden;
}
<div id="outer"><p id="target"></p></div>

Answer №2

Comparing CSS to JavaScript options reveals that they are fundamentally different. Unlike JS, conditional styling cannot be achieved in CSS. However, setting a fixed line height can effectively handle text overflow by truncation.

Key Assumptions

  • The width is a known value
  • The line height is specified

Illustrative Example:

:root {
  --line-height: 1.2rem;
}

html {
  max-width: 20rem;
  line-height: var(--line-height);
}

p {
  --truncate-after: 4;
    max-height: calc(var(--line-height) * var(--truncate-after));
  text-align: justify;
  position: relative;
  overflow: hidden;
  padding-right: 1rem;
  position: relative;
  display: block;
  height: fit-content;
  text-indent: 1rem;
}

p::after {
  content: "...";
  display: block;
  bottom: 3.83rem;
  position: absolute;
  height: 1rem;
  left: -1rem;
}
<p>
  <span>Lorem ipsum dolor sit, amet consectetur adipisicing elit. In sint facilis explicabo voluptatum exercitationem earum. Quibusdam vitae, iusto temporibus corrupti tempore distinctio soluta reiciendis. Ab aspernatur facilis autem temporibus veniam.</span>
</p>

<p>
  <span>Lorem ipsum dolor sit, amet consectetur adipisicing elit.</span>
</p>

<p>
  <span>Lorem ipsum dolor sit, amet consectetur adipisicing elit. S'mores are tasty treats for around campfires.</span>
</p>

Answer №3

To implement this feature, you can utilize the code snippet provided below:

  • Set the height to display the desired number of lines.
  • Hide content exceeding the specified number of lines.
  • Utilize the pseudo element to add ellipsis at the end.
.start-ellipsis {
  height: 55px;
  overflow: hidden;
}
.start-ellipsis::before {
  content: "...";
  display: inline-block;
 }
<p class="start-ellipsis">contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source.</p>

Note:

  • Ensure consistency in font size and family to maintain visual consistency. If you modify the font properties after setting the height, adjust the height accordingly. Define the height after finalizing font settings for best results.
  • Keep in mind that the displayed content may vary based on user's system font settings.

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

Passing Selectize.js load callback to a custom function

I set up selectize.js to gather configuration options from html data attributes. One of the configurations involves specifying a js function for custom data loading (not just simple ajax loading). Everything was working smoothly until I tried running an as ...

Is it possible to utilize JavaScript for displaying a continuous stream of images?

In this scenario, you are tasked with working with an image API and need to send a POST request to retrieve an image stream for display on the rest of your webpage. While I am able to use jQuery to make an ajax request to the service upon page load, I am ...

Ways to align text and horizontal rule perfectly within a div container?

I need to add some text to my <div> container and make sure it is centered. .hr { background: green; height: 50px; margin: 65px 0; width: 3000px; } <div class="hr"></div> This is an illustration of my project: https://i.sstatic.n ...

react Concealing the Card upon clicking a different location

Utilizing a combination of React and TypeScript, this component allows for the card to be toggled between shown and hidden states upon clicking on the specified div tag. However, there is a need to ensure that the card is hidden even if another area outs ...

The webpage does not dynamically adjust to fill the screen size when viewed on an iPhone 6 Plus

I am encountering an issue with a specific page which can be found at the following link: The webpage is not responsive, and the client's requirement is for the entire page to be visible on a mobile screen without the need for zooming in or out. Inst ...

Utilizing JavaScript, HTML, and CSS to incorporate images within circular frames

After finding inspiration from this question about rotating objects around a circle using CSS, I decided to modify the code to include images of Earth orbiting the Sun. The challenge was to make one image orbit another like a planet circling its star. Ear ...

How can I merge an array of objects in lodash?

I am facing a challenge with merging an array of objects in JavaScript. My goal is to combine them into a single object using either a JS library or lodash. Here is how my array looks: [{ 2017: { a: "100", b: "200" ...

Ensuring Safe Definition of HTMLCollectionOf Elements in TypeScript with React

I'm currently working on creating a d3 line chart using react and typescript, and I'm using https://bl.ocks.org/larsenmtl/e3b8b7c2ca4787f77d78f58d41c3da91 as a reference for implementing the mouse over functionality. During one step of the proce ...

Unexpected behavior encountered with JQueryUI modal functionality

Today marks my first experience with JqueryUI. I am attempting to display a conditional modal to notify the user. Within my ajax call, I have this code snippet: .done(function (result) { $('#reportData').append(result); ...

Unable to set $_POST value when using $.ajax post request

I am a beginner in the world of PHP and JavaScript, and I have encountered an issue where I need to make changes to values in an XML document that has been read in. Specifically, I have an HTML Select element that was dynamically generated by PHP code. fu ...

Notation for JavaScript UML component diagrams

When creating connections between entities on a UML diagram, the standard notation is the ball-and-socket/lollipop method. Each pair should include the interface implemented. However, since my project is in JavaScript and doesn't have interfaces, I am ...

Rewriting Next.js with custom headers

My web app allows users to create their own profiles with custom usernames, which can be accessed via the following URLs. ourplatform.com/john ourplatform.com/john/about ourplatform.com/john/contact ourplatform.com/jane ourplatform.com/jane/about ourplatf ...

Using the conditional rendering technique in a mapped function within a React table cell

I have an array that is being displayed inside a Table, and I need to compare each object's "userName" property with the header in order to determine where to place the value. If there is no match, it should display a "0". Here is a snippet of the ta ...

Unable to generate a React Native application

Here are the instructions to develop a react native app: npm install -g create-react-native-app create-react-native-app my-app cd my-app I successfully completed the first step, but I've been encountering challenges with the second step since yeste ...

Tips for Viewing React.js Pages on Your Web Browser

Perhaps this question may sound silly, but as a React beginner, I have been using CDN Links and the "npx create-react-app" functions to build apps. Now, I have some supporting files for a book I am reading, and I want to view the chapters in a w ...

Error message: Component is unable to access the $store property because it is undefined

After doing extensive research and reading numerous similar questions on various platforms, I am still unable to resolve my issue. I have a component containing a login form that triggers a method to dispatch a $store action for logging in the user via fi ...

Is it possible for me to use the name "Date" for my component and still be able to access the built-in "new Date()" functionality?

Currently following the NextJS tutorial, but adding my own twist. In the NextJS example, the custom component is named "Date" (/components/date.js) and does not utilize the built-in Date() object in processing, making it unique to the file. In my scenario ...

Creating tables using ng-repeat in AngularJS and Bootstrap

Although I am new to Angular, I have been struggling with a problem for the past few days and can't seem to find a solution. I want to create a matrix of images (charts generated by angular-chart module) with 2 columns that will dynamically load a va ...

Creating a list using variables through a Post Request in Express

I am currently exploring how to create a list using a Post Request in Express. I am fetching Video Game data from an API and aiming to use this data to populate specific details within a list. For illustration: let name = localStorage.getItem("name"); let ...

Tips for Utilizing JSX Modules in React Typescript App (TSX)

Hello there! I've been using the nft-erc721-collection repository from hashlips-lab for a project I'm currently working on. I've completed the contract part and now I'm looking to make modifications to the dapp within this repository. T ...