English 中文(简体)
在 div 中调整/ 增加字体大小, 使其适合
原标题:Truncate/increase font size within a div so it fits

假设我有一个大小为 div > 100px x 20px ,其中文本随机设置,长度不同,即有些文本部分长,有些短。

因此,当文本数量更少时, div 内就有空白。如果文本数量大,它就会溢出。

My objectives

  • 如果文本小于 div 容量,那么该文本的 font-size 将尽可能地尽量适合该 div ,而不使用 clipping/claypping 。

  • 但如果文本大小大于 div 能力,那么我想将 < emgener > truncate 文本附加为 ... (3点仅) 。

最佳回答

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.

问题回答

我想你需要另一个( 内部) < code@ lt; div> 才能检查文本的高度 。

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

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

然后,你将需要一些简单的函数(像这样的函数):

//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();




相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

image changed but appears the same in browser

I m writing a php script to crop an image. The script overwrites the old image with the new one, but when I reload the page (which is supposed to pickup the new image) I still see the old one. ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!