Find how many lines a text will occupy

css, javascript, php

Solution

One problem that can occur is that the font rendering can be different from browser to browser even in different versions and also on different operation systems. So it's not so easy when it comes to some sort of pre-calculating the text length/height. You could do something like this:

- create a field with the maximum height

- set this field's overflow to hidden

- write a javascript that does the following:

__

- 1 get the text

- 2 cut off the last word (using a regex or something like that)

- 3 check whether the container still has overflow

- 4 do step 2 and 3 so long until there is no more overflow

- 5 cut off one more word (you could still have the case, that you don't have space for "…")

- 6 append "…"

This one only works if you have a plain text. Something like this could totally mess up your HTML-structure if you have tags within the title. Imagine this results in an open "<span>"-tag that never gets closed … :)

Your regex/word finder should also be so clever to cut out things like "words-separated".

I don't know whether this is a very good approach, but maybe a little help, because with jQuery this would only be something like 4-5 lines.

Problem

I have a product listing, in which the title of the product is written. What I want to do is check if the product title is longer than 2 lines, and in that case, print just enough to fit in 2 lines and put "..." in the end. Any ideas?

Original source

Related problems