Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using CSS to hide text that doesn't fit vertically

Tags:

css

If I have something like the following, then how can I hide the lines that don't fully fit? In this example, only the first 2 lines fit fully, with my default font, but the 3rd line only fits partially. I'd like that line to disappear completely (something similar to text-overflow, but for height).

<div style="position: absolute; top: 85%; bottom: 10%; overflow: hidden;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ac condimentum est. Nunc sit amet arcu ut turpis pulvinar fringilla. Mauris et quam bibendum, euismod enim sit amet, tempor ante. Praesent vel consequat sapien, non tristique massa.
</div>

(fiddle)

This is what it looks like for me, and I'd like to get rid of the line after "Mauris et":

like image 476
rid Avatar asked Jan 29 '26 20:01

rid


2 Answers

You can take half of the height of the div and apply that value to the line-height like this:

<div style="height: 2.8em; line-height: 1.4em; overflow: hidden; background: lightblue;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam ac condimentum est. Nunc sit amet arcu ut turpis pulvinar fringilla. Mauris et quam bibendum, euismod enim sit amet, tempor ante. Praesent vel consequat sapien, non tristique massa. Maecenas ultricies semper tellus ac condimentum. Integer imperdiet aliquam sapien, at porta dolor commodo ac. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Pellentesque viverra nulla ut turpis fringilla auctor. In iaculis euismod lorem, ut eleifend libero rhoncus a. Vestibulum egestas rhoncus sem, vel ultricies enim lobortis at.
</div>

This seems to work for any height as long as you set the line-height to a multiple of the container's height. For example, a div with a height of 6.3em with a line-height of 2.1em will fit perfectly (6.3 / 3 = 2.1em). Also, 6.3em / 2 = 3.15em which might be too much spacing but you can take the 3.15em and divide by 2 again to get 1.575em which also fits the text perfectly.

like image 193
Aaron Avatar answered Feb 01 '26 03:02

Aaron


The only thing I know of is a -webkit-line-clamp. There may be other solutions for other browsers. You can also take a look at: http://css-tricks.com/line-clampin/

I would avoid that however and set the height to 2 lines of text if you can. So if the line-height is 15px, set the height to 30px for 2 lines, provided there isn't any other margins or padding.

like image 41
fanfavorite Avatar answered Feb 01 '26 02:02

fanfavorite



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!