Limit text length to n lines using CSS

后端 未结 13 992
滥情空心
滥情空心 2020-11-22 02:53

Is it possible to limit a text length to \"n\" lines using CSS (or cut it when overflows vertically).

text-overflow: ellipsis; only works for 1 line tex

13条回答
  •  不知归路
    2020-11-22 03:09

    I have a solution which works well but instead an ellipsis it uses a gradient. It works when you have dynamic text so you don't know if it will be long enough to need an ellipse. The advantages are that you don't have to do any JavaScript calculations and it works for variable width containers including table cells and is cross-browser. It uses a couple of extra divs, but it's very easy to implement.

    Markup:

    
        
    content goes here

    CSS:

    .fade-container { /*two lines*/
        overflow: hidden;
        position: relative;
        line-height: 18px; 
        /* height must be a multiple of line-height for how many rows you want to show (height = line-height x rows) */
        height: 36px;
        -ms-hyphens: auto;
        -webkit-hyphens: auto;
        hyphens: auto;
        word-wrap: break-word;
    }
    
    .fade {
            position: absolute;
            top: 50%;/* only cover the last line. If this wrapped to 3 lines it would be 33% or the height of one line */
            right: 0;
            bottom: 0;
            width: 26px;
            background: linear-gradient(to right,  rgba(255,255,255,0) 0%,rgba(255,255,255,1) 100%);
    }
    

    blog post: http://salzerdesign.com/blog/?p=453

    example page: http://salzerdesign.com/test/fade.html

提交回复
热议问题