Limit text length to n lines using CSS

后端 未结 13 1015
滥情空心
滥情空心 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:19

    I really like line-clamp, but no support for firefox yet.. so i go with a math calc and just hide the overflow

    .body-content.body-overflow-hidden h5 {
        max-height: 62px;/* font-size * line-height * lines-to-show(4 in this case) 63px if you go with jquery */
        overflow: hidden;
    }
    .body-content h5 {
        font-size: 14px; /* need to know this*/
        line-height:1,1; /*and this*/
    }
    

    now lets say you want to remove and add this class via jQuery with a link, you will need to have an extra pixel so the max-height it will be 63 px, this is because you need to check every time if the height greather than 62px, but in the case of 4 lines you will get a false true, so an extra pixel will fix this and it will no create any extra problems

    i will paste a coffeescript for this just to be an example, uses a couple of links that are hidden by default, with classes read-more and read-less, it will remove the ones that the overflow is not need it and remove the body-overflow classes

    jQuery ->
    
        $('.read-more').each ->
            if $(this).parent().find("h5").height() < 63
                 $(this).parent().removeClass("body-overflow-hidden").find(".read-less").remove()
                 $(this).remove()
            else
                $(this).show()
    
        $('.read-more').click (event) ->
            event.preventDefault()
            $(this).parent().removeClass("body-overflow-hidden")
            $(this).hide()
            $(this).parent().find('.read-less').show()
    
        $('.read-less').click (event) ->
            event.preventDefault()
            $(this).parent().addClass("body-overflow-hidden")
            $(this).hide()
            $(this).parent().find('.read-more').show()
    
    0 讨论(0)
提交回复
热议问题