Reputation: 4040
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 div expands resize according to length of th text inserted. I tried :
#div1
{
width:auto;
}
but it is not working. Please help.
Upvotes: 5
Views: 13508
Reputation: 5048
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.
Upvotes: 0
Reputation: 101483
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());
});
Upvotes: 9
Reputation: 805
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.
Upvotes: 1
Reputation: 21
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.
Tested IE7 IE8 IE9.
Upvotes: 2
Reputation: 328604
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.
Upvotes: 2