javascript - 如何动态调整 DIV 元素的宽度以适应其文本内容?

标签 javascript html css

假设我有这个 HTML 代码片段:

<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

我想知道如何动态调整 divtextContent 宽度,以便它很好地适合其文本内容(文本不会换行滚动 chop )。

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

我愿意接受任何使用 CSS 和/或 JavaScript 的解决方案。

最佳答案

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

假设内容适合而不会溢出,您可以使用没有设置宽度的 float (CSS 2.1 或更高版本不需要宽度)。如果没有更多细节,我无法建议将它放在哪里或设置哪些其他属性来获得所需的效果(例如, float 围绕以下内容向下 float ,因此请将其放在段落的开头)。

如果您不关心在旧浏览器(如 Internet Explorer)上看起来完美的效果,您可以使用 display: tabledisplay: table-cell,与注意 table 不会溢出:它们会拉伸(stretch)。如果您想避免 div 溢出,但允许它溢出视口(viewport)——例如,水平滚动的电影胶片,那么这种拉伸(stretch)可能是可取的。在这种情况下,altCognito 关于 white-space: nowrap 的建议将非常有用。

关于javascript - 如何动态调整 DIV 元素的宽度以适应其文本内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/847527/

相关文章:

javascript - react /通量 : Firing an action from a render method of an component or doing a Rest call from a component?

javascript - JavaScript 构造函数中相同的变量名和属性名

HTML/CSS 水平对齐单选和图像标签

html - CSS:以 Rails 的 `form_for` 生成的形式扩展输入框?

html - 不透明度不起作用

html - 在 HTML 元素中 float 的 CSS3 动画

javascript - Angular + php 不会从非 index.html 将数据加载到服务器

javascript - angularjs Controller 内的动态表

javascript - 按钮不适用于移动设备,但适用于 PC Bootstrap

html - 当我可以使用自己的标签时,为什么要使用 "class="?