Niraj Choubey
Niraj Choubey

Reputation: 4040

How to auto grow (width) of a div

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

Answers (6)

ngShravil.py
ngShravil.py

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

Bojangles
Bojangles

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

3Dom
3Dom

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

Jat
Jat

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.

http://jsfiddle.net/gAcjn/3/

Tested IE7 IE8 IE9.

Upvotes: 2

Hussein
Hussein

Reputation: 42818

Check working example at http://jsfiddle.net/9LAg9/2/

Upvotes: 2

Aaron Digulla
Aaron Digulla

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

Related Questions