Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto grow (width) of a div

Tags:

jquery

css

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.

like image 347
Niraj Choubey Avatar asked Mar 07 '11 09:03

Niraj Choubey


2 Answers

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());
});
like image 94
Bojangles Avatar answered Oct 25 '22 13:10

Bojangles


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.

like image 43
Aaron Digulla Avatar answered Oct 25 '22 12:10

Aaron Digulla