34

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

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

Can I rely on the fact that height of one row = 2.5ex or is that just a coincidence in the browsers I am using to test?

4 Answers 4

47

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

2
3

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.

2
  • how can I use this inside a flex div with 2 items? let's say an svg icon + a 2 line clamp div in a row flex div. thanks! Commented Nov 5, 2020 at 16:50
  • This was the right solution for me and the feature now works on all major browsers.
    – NTR
    Commented Oct 26, 2023 at 15:57
3

Use rem:

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.