How to set element height for a fixed number of lines of text

后端 未结 5 658
攒了一身酷
攒了一身酷 2021-02-05 02:54

Given some text that occupies about 10 rows, how can I resize its container to only show the first 3 rows and hide the others? Apparently this works, but I think it is not relia

相关标签:
5条回答
  • 2021-02-05 03:25

    you can set the line height of a text and with it knows the exact height of each row and set desired height of your container, simply doing this:

    .container {
        line-height:25px;
        height:75px;
        overflow:hidden;
    }
    

    Now everything works rightly :)

    0 讨论(0)
  • 2021-02-05 03:27

    The ex unit is the font x-height (height of its x character). I would not use this here. You should use the em unit. This is the actual font-height. The font-height is defined by setting the line-height property. So:

    .container {
        height: 3em; /* 1em for each visible line */
        overflow: hidden;
    }
    

    Here is some more info on CSS length units: http://www.w3.org/TR/CSS21/syndata.html#length-units

    0 讨论(0)
  • 2021-02-05 03:29

    You can use the webkit property line-clamp

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

    It doesn't work on all browsers, but hopefully it will one day.

    0 讨论(0)
  • 2021-02-05 03:37

    Use rem:

    .container {
        height: 3rem; /* 1rem for each visible line */
        overflow: hidden;
    }
    
    0 讨论(0)
  • 2021-02-05 03:40

    If you are going to use this you should ensure the line-height is always 2.5ex

    .container {
      line-height: 2.5ex;
      height: 7.5ex; /* 2.5ex for each visible line */
      overflow: hidden;
    }
    

    Demo

    0 讨论(0)
提交回复
热议问题