Home > Web Front-end > JS Tutorial > body text

How can we append ellipses (...) to indicate truncation on a multi-line `` element with a fixed width and height?

DDD
Release: 2024-10-27 08:23:30
Original
521 people have browsed it

How can we append ellipses (...) to indicate truncation on a multi-line `` element with a fixed width and height?

Ellipsis Handling for Fixed-Width, Multi-Line Text Overflow

In the realm of web development, the need arises to elegantly handle text overflow within a container with specified width and height. How can we append ellipses (...) to indicate truncation on a multi-line

element?

Possible Solution:

jQuery offers a solution with the following markup and CSS:

<code class="html"><div id="fos">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>
</div></code>
Copy after login
<code class="css">#fos {
  width: 300px;
  height: 190px;
  overflow: hidden;
}
#fos p {
  padding: 10px;
  margin: 0;
}</code>
Copy after login

The jQuery code repeatedly trims the last word of the text until the desired height is reached:

<code class="javascript">var $p = $('#fos p');
var divh = $('#fos').height();
while ($p.outerHeight() > divh) {
  $p.text(function (index, text) {
    return text.replace(/\W*\s(\S)*$/, '...');
  });
}</code>
Copy after login

Considerations:

  • This technique ensures a visually correct result, even with JavaScript disabled.
  • Server-side truncation can improve performance.
  • This is an incomplete solution and requires further refinement for a practical implementation.

Demonstration:

A live demonstration is available on jsFiddle: https://jsfiddle.net/5638d9y0/

Additional Resources:

  • [CSS Flexible Box Tutorial](https://css-tricks.com/snippets/css/a-guide-to-flexbox/)
  • [Introducing Flexbox](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout/Using_CSS_flexible_boxes)
  • [A Complete Guide to Flexbox](https://www.w3schools.com/css/css3_flexbox.asp)

The above is the detailed content of How can we append ellipses (...) to indicate truncation on a multi-line `` element with a fixed width and height?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template