Cross-browser multi-line text overflow with ellipsis appended within a fixed width and height

前端 未结 25 2437
栀梦
栀梦 2020-11-22 16:19

I made an image for this question to make it easier to understand.

Is it possible to create an ellipsis on a

with a fixed width and multiple
相关标签:
25条回答
  • 2020-11-22 16:27

    There is no such feature in HTML, and this is very frustrating.

    I have developed a library to deal with this.

    • Multiline text-overflow: ellipsis
    • Multiline text with technologies that does not support it: SVG, Canvas for example
    • Have exactly the same line breaks in your SVG text, in your HTML rendering, and in your PDF export for example

    Check out my site for screenshot, tutorial, and dowload link.

    0 讨论(0)
  • 2020-11-22 16:30

    Javascript libraries for "line clamping"

    Note that "line clamping" is also referred as "Ellipsis on block of multi-lines" or "vertical ellipsis".


    github.com/BeSite/jQuery.dotdotdot

    • Pros: 2.5Kb (minified & gzipped), no big activity on repo but not bad either
    • Cons: jQuery dependency, paid for commercial use (CC-BY-NC-4.0 license)
    • my 2 cents: stackoverflow.com/questions/25187774/read-more-and-read-less-with-dotdotdot-jquery/29118739#29118739
    • helpful stackoverflow.com/questions/19015945/jquery-dotdotdot-expand-truncate-text-onclick
    • helpful gist.github.com/chiragparekh/c7e33dc749ed25544bde

    github.com/josephschmitt/Clamp.js

    • Cons: code repo barely active
    • informative reusablebits.com/post/2980974411/clamp-js-v0-2-explanations-and-performance

    Here are a few more I did not investigate yet:

    • github.com/ftlabs/ftellipsis
    • github.com/micjamking/Succinct
    • github.com/pvdspek/jquery.autoellipsis and pvdspek.github.io/jquery.autoellipsis
    • github.com/rviscomi/trunk8
    • github.com/dobiatowski/jQuery.FastEllipsis
    • github.com/theproductguy/ThreeDots
    • github.com/tbasse/jquery-truncate
    • github.com/kbwood/more

    CSS solutions for line clamping

    There are some CSS solutions, but the simplest uses -webkit-line-clamp which has poor browser support. See live demo on jsfiddle.net/AdrienBe/jthu55v7/

    Many people went to great efforts in order to make this happen using CSS only. See articles and questions about it:

    • css-tricks.com/line-clampin : 5 stars article on line camplin
    • mobify.com/blog/multiline-ellipsis-in-pure-css : CSS only
    • cssmojo.com/line-clamp_for_non_webkit-based_browsers/ : "mimic" -webkit-line-clamp in non webkit browsers
    • With CSS, use "..." for overflowed block of multi-lines
    • Cross-browser multi-line text overflow with ellipsis appended within a width and height fixed `<div>`
    • How to display only the first few lines of a div (clamping)?
    • jquery limit lines in a paragraph and apply three periods to the end
    • Limit text length to n lines using CSS

    What I'd recommend

    Keep it simple. Unless you have great amount of time to dedicate to this feature, go for the simplest & tested solution: simple CSS or a well tested javascript library.

    Go for something fancy/complex/highly-customized & you will pay the price for this down the road.


    What others do

    Having a fade out like Airbnb does might be a good solution. It probably is basic CSS coupled with basic jQuery. Actually, it seems very similar to this solution on CSSTricks

    Oh, and if you look for design inspirations:

    • smashingmagazine.com/2009/07/designing-read-more-and-continue-reading-links/, from 2009 though...
    • Dribbble probably has interesting designs...I could not find a way to gather them though (via search or tags), feel free to share a relevant link
    0 讨论(0)
  • 2020-11-22 16:30

    Found this short CSS-only solution in Adrien Be's answer:

    .line-clamp {
      display: -webkit-box;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical; 
      overflow: hidden; 
    }
    

    As of March 2020 browser support is 95.3%, not being supported in IE and Opera Mini. Works on Chrome, Safari, Firefox and Edge.

    0 讨论(0)
  • 2020-11-22 16:31

    not sure if this is what you're looking for, it uses min-height instead of height.

        <div id="content" style="min-height:10px;width:190px;background:lightblue;">
        <?php 
            function truncate($text,$numb) {
                // source: www.kigoobe.com, please keep this if you are using the function
                $text = html_entity_decode($text, ENT_QUOTES);
                if (strlen($text) > $numb) {
                    $text = substr($text, 0, $numb);
                    $etc = "..."; 
                    $text = $text.$etc;
                } 
                $text = htmlentities($text, ENT_QUOTES);
                return $text;
            }
            echo truncate("this is a multi-lines text block, some lines inside the div, while some outside", 63);
        ?>
        </div>
    
    0 讨论(0)
  • 2020-11-22 16:33

    Here's a vanilla JavaScript solution you can use in a pinch:

    // @param 1 = element containing text to truncate
    // @param 2 = the maximum number of lines to show
    function limitLines(el, nLines) {
      var nHeight,
        el2 = el.cloneNode(true);
      // Create clone to determine line height
      el2.style.position = 'absolute';
      el2.style.top = '0';
      el2.style.width = '10%';
      el2.style.overflow = 'hidden';
      el2.style.visibility = 'hidden';
      el2.style.whiteSpace = 'nowrap';
      el.parentNode.appendChild(el2);
      nHeight = (el2.clientHeight+2)*nLines; // Add 2 pixels of slack
      // Clean up
      el.parentNode.removeChild(el2);
      el2 = null;
      // Truncate until desired nLines reached
      if (el.clientHeight > nHeight) {
        var i = 0,
          imax = nLines * 35;
        while (el.clientHeight > nHeight) {
          el.innerHTML = el.textContent.slice(0, -2) + '&hellip;';
          ++i;
          // Prevent infinite loop in "print" media query caused by
          // Bootstrap 3 CSS: a[href]:after { content:" (" attr(href) ")"; }
          if (i===imax) break;
        }
      }
    }
    
    limitLines(document.getElementById('target'), 7);
    #test {
      width: 320px;
      font-size: 18px;
    }
    <div id="test">
      <p>Paragraph 1</p>
      <p id="target">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
      <p>Paragraph 3</p>
    </div>

    You can play around with it in the codepen below. Try changing the font size in the CSS panel and make a minor edit in the HTML panel (e.g., add an extra space somewhere) to update the results. Regardless of the font size, the middle paragraph should always be truncated to the number of lines in the second parameter passed to limitLines().

    Codepen: http://codepen.io/thdoan/pen/BoXbEK

    0 讨论(0)
  • 2020-11-22 16:36

    Very simple javascript solution. Divs has to be styled f.e.:

    .croppedTexts { 
      max-height: 32px;
      overflow: hidden;
    }
    

    And JS:

    var list = document.body.getElementsByClassName("croppedTexts");
    for (var i = 0; i < list.length; i++) {
      cropTextToFit(list[i]);
    }
    
    function cropTextToFit (o) {
      var lastIndex;
      var txt = o.innerHTML;
      if (!o.title) o.title = txt;
    
      while (o.scrollHeight > o.clientHeight) {
        lastIndex = txt.lastIndexOf(" ");
        if (lastIndex == -1) return;
        txt = txt.substring(0, lastIndex);
        o.innerHTML = txt + "…";
      }
    }
    
    0 讨论(0)
提交回复
热议问题