简体   繁体   中英

Check how many lines will a <p> tag occupy

I was wandering, is there a way to check how many lines will a text in a <p> tag occupy after beeng wrapped? I know the width & height of <div> that contains this <p> .

This question came up when I was trying to cut a text if it's more then 3 lines long, and make it expandable later. I know I can achieve this by cutting the text with fixed length (average symbol count in a line). But I was just wandering :)

you don't actually need to know how many pixels the text is long if you use relative units for font-size, line-height and height: see this fiddle - http://jsfiddle.net/6WRsg/

I set a line-height: 1.3 and height: 3.9em /* (1.3 * 3 lines) */ ; so no matter what the font-size is, you always display at most three lines of text.

When you need to show all the content just switch programmatically (via javascript) the height to auto

You could place the para temporarily miles outside the visible page with position:absolute, left:-2000px and then check its offsetHeight to get an idea of how many lines it will have. Not sure how you'd find exact line breaks tho.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM