简体   繁体   English

优化具有固定高度的div的宽度? (即仍然适合文本的最小宽度)

[英]Optimizing the width of a div with a fixed height? (i.e. smallest width that will still fit the text)

I have a div that contains a variable amount of text, and a fixed height. 我有一个div,其中包含可变数量的文本和固定的高度。 Without a fixed width, the width would automatically be 100%. 如果没有固定的宽度,则宽度将自动为100%。 I could estimate the width that the div would need to be, but since the text will not always be the same, this will not always work. 我可以估计div所需的宽度,但是由于文本并不总是相同,因此这并不总是有效。 It would need to automatically be determined each time. 每次都需要自动确定。 Basically, I want the width of the div to be determined by the content. 基本上,我希望div的宽度由内容决定。

Simply, my div would be something like 简而言之,我的div就像

#a {
height:100px;
width:?;
}

Consider these: http://jsfiddle.net/ZE4Sy/2/ 考虑这些: http : //jsfiddle.net/ZE4Sy/2/

This is essentially what my goal is (though I did this by estimating the widths). 从本质上讲,这就是我的目标(尽管我是通过估算宽度来做到这一点的)。 Each div has a fixed height, but a different amount of text. 每个div都有固定的高度,但文本量却不同。 I made the widths as small as they could be before the text began exceeding the height. 在文字开始超过高度之前,我将宽度设置得尽可能小。

I only have a very basic knowledge of jquery/javascript, but I'm assuming that if there is a solution to this, it may involve those. 我只具有jquery / javascript的非常基础的知识,但我假设如果对此有解决方案,则可能涉及到这些。

Thank you for your help! 谢谢您的帮助!

Here: 这里:

$('.box').each(function () { 
    var $box = $(this),
        width = $box.width(),
        $inner = $box.wrapInner('<div></div>').children().first();

    while (width > 0 && $inner.height() < $box.height()) $box.width(--width);  
    $box.width(++width);
});

Live demo: http://jsfiddle.net/ZE4Sy/6/ 现场演示: http //jsfiddle.net/ZE4Sy/6/

I had a similar issue but in my case there were two factors that prevented Šime Vidas' solution from working, which were that the content in my div contained HTML (p tags with margins, etc), and I wanted the div to protrude outside of the available width of the containing div if necessary. 我遇到了类似的问题,但就我而言,有两个因素使ŠimeVidas的解决方案无法正常工作,即我的div中的内容包含HTML(带有边距的p标签等),并且我希望div突出到外部如有必要,包含div的可用宽度。 Using his solution for inspiration, I came up with this: 利用他的解决方案获得灵感,我想到了:

$('.box').each(function () { 
    $box = $(this);
    $inner = $box.wrapInner('<div></div>');
    while ($inner[0].scrollHeight > $box.height()) $box.width($box.width()+100);  
});

Which simply keeps widening the box a little until the height of the inner div doesn't overrun the containing one. 只是简单地使框变宽一点,直到内部div的高度不超过包含该框的那个。 You could reduce the +100 figure to get a more accurate width, at the expense of processing time. 您可以减少+100数字以获得更准确的宽度,但会浪费处理时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM