I have a div
<div id="div1">
</div>
and i am inserting text into it using jquery :
$('#div1').html('abcd');
I want width of this di开发者_开发知识库v expands resize according to length of th text inserted. I tried :
#div1
{
width:auto;
}
but it is not working. Please help.
I think what you want here is inline-block
. I've made a JSFiddle for you here, which should do what you want. Type into the textbox and see the div underneath expand as the text does.
HTML
<input type="text" id="input">
<div>
<div id="out"></div>
</div>
jQuery
$("#input").keyup(function() {
$("#out").html($(this).val());
});
The default width of a div
is auto
which means "the width of the parent".
If you need an element which changes width according to its contents, you need an inline element like span
.
The only non-inline HTML element which scales with its content is a table
. If you don't specify a width for a table, it will grow with its content.
Check working example at http://jsfiddle.net/9LAg9/2/
My Requirement was same and little different and also want to it work same in ie7+.
Requirement was width according to its content and auto center the div.
Check this out working example.
http://jsfiddle.net/gAcjn/3/
Tested IE7 IE8 IE9.
Don't leave that poor little div
all alone.
Just put another one next to it like this, or your lonely div will expand to the width of the window. Also, the default value for a div
's width is auto, so no point specifying that.
<div style="float:left; border:1px solid #fa0237;">Your inserted text</div>
<div style="float:left;"></div>
The 2nd div
pushes up against the right of the 1st div
, forcing it to assume its minimum allowed width.
You can easily do this with CSS, use fit-content
property of width
, like below:
#div1 {
width: fit-content;
}
This will allow the div
element to auto grow.
P.S. : No need of complex JQuereis. Let me know if this was helpful to you.
精彩评论