如何动态调整DIV元素的宽度以适应其文本内容? [英] How can I dynamically resize a DIV element's width to fit its text content?

查看:126
本文介绍了如何动态调整DIV元素的宽度以适应其文本内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个HTML代码段:

 < div id =container> 
< div id =textContent>文字内容Te< / div>
< div id =anotherText>另一个文字内容< / div>
< / div>

原始HTML输出http://img26.imageshack.us/img26/1571/beforeeffect.gif



我想知道我如何动态调整 div textContent 宽度,以便它很好地符合其文本内容(文本都不会包装滚动截断)。 所需的HTML输出http://img26.imageshack.us/img26/5851/desiredeffect.gif p>

我可以使用任何CSS和/或JavaScript解决方案。

>

我不知道如何动态
调整div宽度以适应
文本内容(不包装)?

假设内容不会溢出,您就可以使用d使用没有设置宽度的浮动(在CSS 2.1或更高版本中不需要宽度)。没有更多细节,我无法建议将它放在哪里,或者设置什么其他属性来获得所需的效果(例如,将浮动内容放在下面的内容周围,以便将其放在段落的开头)。



如果您不担心在Internet Explorer等旧浏览器上看起来完美的效果,可以使用 display:table display:table-cell ,注意表不会溢出:它们伸展。如果您想避免div溢出,但允许它溢出视口 - 例如水平滚动的电影胶片,则可能需要拉伸。在这种情况下,altCognito建议 white-space:nowrap 会非常有用。


Let say I have this HTML code snippet:

<div id="container">
<div id="textContent">Text Content Te</div>
<div id="anotherText">Another Text Content</div>
</div>

Original HTML output http://img26.imageshack.us/img26/1571/beforeeffect.gif

I wonder how I could dynamically resize the div's textContent width so that it fits its text content nicely (neither the text will be wrapping nor scrolling nor truncated).

Desired HTML output http://img26.imageshack.us/img26/5851/desiredeffect.gif

I am open to any solution using CSS and/or JavaScript.

解决方案

I wonder how could I dynamically resized the div's width to fit the text content (without wrapping)?

Assuming the content would fit without overflowing, you could use a float without a width set (width isn't required in CSS 2.1 or greater). Without more detail, I can't suggest where to put it or what other properties to set to get the desired effect (eg, floats float down around following content, so put it at the beginning of a paragraph).

If you're not concerned with the effect looking perfect on old browsers like Internet Explorer, you could use display: table or display: table-cell, with the caveat that tables don't overflow: they stretch. That stretching may be desirable if you want to avoid overflow of your div, but allow it to overlow the viewport -- eg, a film strip that scrolls horizontally. In that case, altCognito's suggestion of white-space: nowrap would be very useful.

这篇关于如何动态调整DIV元素的宽度以适应其文本内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆