Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically resize a DIV element's width to fit its text content?

Let say I have this HTML code snippet:

<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

I wonder how I could dynamically resize the div's textContent width so that it fits its text content nicely (neither the text will be wrapping nor scrolling nor truncated).

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

I am open to any solution using CSS and/or JavaScript.

like image 421
Nordin Avatar asked May 11 '09 10:05

Nordin


People also ask

How do I change the size of a div dynamically?

The content height of a div can dynamically set or change using height(), innerHeight(), and outerHeight() methods depending upon the user requirement.

How do you make div width expand with its content using CSS?

Syntax: width: length|percentage|auto|initial|inherit; Property Values: width: auto; It is used to set width property to its default value.


2 Answers

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

Assuming the content would fit without overflowing, you could use a float without a width set (width isn't required in CSS 2.1 or greater). Without more detail, I can't suggest where to put it or what other properties to set to get the desired effect (eg, floats float down around following content, so put it at the beginning of a paragraph).

If you're not concerned with the effect looking perfect on old browsers like Internet Explorer, you could use display: table or display: table-cell, with the caveat that tables don't overflow: they stretch. That stretching may be desirable if you want to avoid overflow of your div, but allow it to overlow the viewport -- eg, a film strip that scrolls horizontally. In that case, altCognito's suggestion of white-space: nowrap would be very useful.

like image 118
Anonymous Avatar answered Oct 23 '22 02:10

Anonymous


<style>
div {
  white-space: nowrap;
}
</style>

This will do the trick (though you probably should be more specific about the divs that you want to change. This means the divs that you do use this on won't have any line feeds unless you specify them yourself. But I'm guessing you're using this for labels, so you should be all set.

See an example.

like image 6
cgp Avatar answered Oct 23 '22 01:10

cgp