3

Suppose I have a div element with height: 150px and width:300px. Is it possible to calculate how many lines of text can it be reside within it without overflow, where text have predefined font-size, line-height and other text properties?

My Main Objective:

I have html like this:

<div id="parent">
    <div>[Title]</div>
    <div>[Description]</div>
    <div>[Buttons]</div>
</div>

In [Description] div I have to display exactly eight lines of description where description comes form DB and size may be much or less. And the last lines will truncate with ... at the end. How can I achieve my goal?

Pleas help me.

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164

2 Answers2

2

Yes, there is a way to only show 8 lines. Basically, what you can do is add each word individually, and every time you add a word, check if the height of your div has changed. Count how many times it changes, and if more than 8, stop adding words.

var text = "Lorem ipsum dolor sit amet...";

var changesInHeight = 0,
    prevHeight = 0,
    words = text.split(" ");
    div = document.getElementsByTagName("div")[0];
for(var i = 0; i < words.length; i++) {
    var prevText = div.innerHTML;
    div.innerHTML += words[i] + " ";

    var height = div.getClientRects()[0].height;
    if (height > prevHeight)
        changesInHeight++;
    prevHeight = height;

    if (changesInHeight > 8) {
        div.innerHTML = prevText + "...";
        break;
    } 
}

Live example

If you need to support IE, getClientRects()[0] won't have a height property, but it has a bottom and top which you can substract to get the height.

That was fun, if you have any questions don't hesitate to ask in the comments.

Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
1

only if you use a monospace font (one with fixed character dimensions). If your not using monospaced and you need very good accuracy then you'll probably need to look into imagick type solutions by either creating and reading an image of the text, or reading the chracter map. Which is overkill to say the least.

Edit:

Thought id just post up what you need to be looking at for accurate measurement

Imagick::queryFontMetrics <-- Google it and read a few pages, the PHP Docs aren't very useful

Lee
  • 10,496
  • 4
  • 37
  • 45
  • I believe the OP is talking about the height of the lines here. It doesn't matter what font, monospaced or not, in this case. – Alex Turpin Nov 28 '11 at 16:17