Truncate / increase font size in div to fit

Suppose I have a divsize 100px x 20px, and the text inside it is 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 empty space in the div. And if there is a large amount of text, it overflows.

My goals

  • If the text is less than capacity div, then font-sizethis text will be as close to this divas possible without clipping / cutting .

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

+3
source share
2 answers

In the first part, I suggest wrapping the text in <span>so that you can get it offsetWidth, then you can set its style property font-sizeto 200 / span.offsetWidth. Keep in mind that these are rough calculations with some approximations, and perhaps you want to do better using 190 or 195 instead of 200.

For the second part, just install overflow: hidden; text-overflow: ellipsis; white-space: nowrap;. Keep in mind that dots with ellipses do not appear in older Firefox clients.

+4
source

I think you will need one more (internal) <div>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();
0
source

All Articles