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?
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?
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:
__
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.
I ended up doing something like this:
<p id="titleContainer">blabla bla bla blablabla bla blabla bla bla blablabla bla blabla bla bla blablabla bla</p>
<script type="text/javascript">
function checkOverflow(el){
var curOverflow = el.style.overflow;
if ( !curOverflow || curOverflow === "visible" ){
el.style.overflow = "hidden";
}
// 26 pixels was the height of 2 lines
var isOverflowing = el.scrollHeight > 26;
el.style.overflow = curOverflow;
return isOverflowing;
}
var titleContainer = document.getElementById("titleContainer");
var titleTxt = titleContainer.innerHTML + "...";
while(checkOverflow(titleContainer)){
titleTxt = titleTxt.replace(/ [^ ]+\.\.\.$/, "...");
titleContainer.innerHTML = titleTxt;
}
</script>
You'll need to play around with your design to see approximately how many characters will equal two lines. If you're not using a fixed-with font, you'll have to look at a bunch of cases.
I use this function to do this on one of my sites. This trims to a certain max number of characters, then breaks the string at the first space before the end of the string.
function str_tr($string,$max)
{
if(strlen($string)>$max)
{
$string = substr($string,0,$max);
$i = strrpos($string," ");
$string = substr($string,0,$i);
$string .= "...";
}
return $string;
}
As @cpilko said… if it's not a fixed size font… it won't work for sure…
30 i (small char) versus w (big char) in non fixed fonts
iiiiiiiiiiiiiiiiiiiiiiiiiiiiii
wwwwwwwwwwwwwwwwwwwwwwwwwwwwww
But, in fixed size fonts… things are more predictable:
iiiiiiiiiiiiiiiiiiiiiiiiiiiiii
wwwwwwwwwwwwwwwwwwwwwwwwwwwwww
What you need is the text-overflow CSS property. It uses CSS to cut off excess text in a container of a fixed width and replaces the overflow with an ellipsis character. Read more at: