Home > Web Front-end > CSS Tutorial > How to Create Multi-Line Text Overflow with Ellipsis in a Fixed-Width Div?

How to Create Multi-Line Text Overflow with Ellipsis in a Fixed-Width Div?

Mary-Kate Olsen
Release: 2024-12-26 17:18:09
Original
974 people have browsed it

How to Create Multi-Line Text Overflow with Ellipsis in a Fixed-Width Div?

Cross-browser Multi-Line Text Overflow with Appended Ellipsis in a Fixed Width and Height

Problem:

How can we create an ellipsis on a <div> with a fixed width and multiple lines, ensuring that the overflowed text is truncated?

Solution:

To achieve this, we can utilize a jQuery snippet to repeatedly remove the last word of the text until it fits within the desired height.

Implementation:

  1. Define the HTML markup for the <div> with a fixed width and height, and a paragraph (

    ) to contain the text.

  2. Add the CSS to set the overflow to hidden, ensuring that the truncation remains invisible.
  3. Create a jQuery function to perform the truncation. This function will:

    • Retrieve the

      element and store it in the $p variable.

    • Calculate the height of the <div> and store it in the divh variable.
    • Use a while loop to remove the last word of the text until it fits within the desired height. The loop uses the text() function to update the content of the

      with the updated, truncated text.

Additional Considerations:

  1. This approach involves JavaScript for truncation. Consider combining it with server-side truncation to improve performance.
  2. Add a width: 100% to the

    CSS to ensure it takes up the full width of the <div>.

Example:

HTML

<div>
Copy after login

CSS

#fos {
  width: 300px;
  height: 190px;
  overflow: hidden;
}

#fos p {
  width: 100%;
  padding: 10px;
  margin: 0;
}
Copy after login

jQuery

var $p = $('#fos p');
var divh = $('#fos').height();

while ($p.outerHeight() > divh) {
  $p.text(function (index, text) {
    return text.replace(/\W*\s(\S)*$/, '...');
  });
}
Copy after login

Demo: https://jsfiddle.net/w0n5cy2j/

The above is the detailed content of How to Create Multi-Line Text Overflow with Ellipsis in a Fixed-Width Div?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template