3

Suppose I have a div of size 100px x 20px and text within it set randomly with different lengths i.e. some text sections are long and some are short.

So, when the amount of text is less, then there is blank space within the div. And if there is large amount of text, it overflows.

My objectives

  • If text is less than the div capacity, then the font-size of that text will maximize to fit within that div as much as possible without clipping/ cutting.

  • But if text size is larger than the div capacity then I want to truncate text and append ... (3 dots only).

Community
  • 1
  • 1
The System Restart
  • 2,873
  • 19
  • 28
  • I think [this post](http://stackoverflow.com/questions/2059743/detect-elements-overflow-using-jquery) is a bit similar, and can give you a start. – iddo May 21 '12 at 09:17

2 Answers2

4

For the first part, I'd suggest to wrap the text in a <span> so you can get its offsetWidth, then you can set its font-size style property to 200 / span.offsetWidth. Keep in mind, though, that this is a rough calculations with some approximations being made, and maybe you want to do better using 190 or 195 instead of 200.

For the second part, just set overflow: hidden; text-overflow: ellipsis; white-space: nowrap;. Keep in mind that the ellipsis dots don't appear in older Firefox clients.

MaxArt
  • 22,200
  • 10
  • 82
  • 81
0

I think you will need another (inner) <div> in order to be able to check the height of the text.

<div id="mainDiv">
    <div class="inner">
        <p>Some text</p>
    </div>
</div>

//css
#mainDiv
{
    width: 200px;
    height: 50px;
    overflow: hidden;
}

Then you will need some simple functions (something like this):

//pseudocode

function doCheck()
{
    if (".inner".height > "#mainDiv".height) truncate()
    else increaseSize()
}

function truncate()
{
    for (i = 1; i <= ".inner".wordCount)
    while (".inner".height <= "#mainDiv".height)
    {
        addOneMoreWord() + " …";
        if (".inner".height > "#mainDiv".height) removeLastWord()
    }
}
//similar thing for increaseSize();
strah
  • 6,702
  • 4
  • 33
  • 45