Home  >  Article  >  Web Front-end  >  How to Implement Ellipsis for Multi-line Text Overflow within a Fixed Container?

How to Implement Ellipsis for Multi-line Text Overflow within a Fixed Container?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 16:17:03724browse

 How to Implement Ellipsis for Multi-line Text Overflow within a Fixed Container?

Ellipsis Handling for Multi-line Overflow within a Fixed Container

In web development, it's often necessary to display multi-line text within a container of specified width and height. However, when the text exceeds the available space, it can create an unsightly overflow. To address this, developers often seek methods to implement an ellipsis, indicating that there's more text that is hidden.

One such scenario is where the text is contained within a

element with both fixed width and height. While various jQuery plugins exist, finding the perfect solution can be challenging. This article explores a basic yet effective approach to achieving the desired result.

Using jQuery provides a convenient way to manipulate the text content of the

element. Our goal is to iteratively remove the last word until the text height fits within the specified container height. This is accomplished by leveraging the outerHeight() function to check if the text height exceeds the container height and, if true, using the text() function to truncate the last word from the text.

To ensure that the overflow remains invisible, we utilize the overflow: hidden; CSS property on the

element. This way, even if JavaScript is disabled, the result appears visually correct without the ellipsis.

Here's the CSS and jQuery code for this solution:

<code class="css">#fos { width: 300px; height: 190px; overflow: hidden; }
#fos p { padding: 10px; margin: 0; }</code>
<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>

This approach offers a simple and efficient solution to the problem of multi-line text overflow with ellipsis handling within a container of fixed width and height. By combining jQuery with CSS, you can achieve the desired visual effect while maintaining accessibility even when JavaScript is disabled.

The above is the detailed content of How to Implement Ellipsis for Multi-line Text Overflow within a Fixed Container?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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