Resize <div> automatically based on text?

lhan picture lhan · Apr 16, 2013 · Viewed 67.2k times · Source

I've got the following JS Fiddle to demonstrate what I'm trying to accomplish: http://jsfiddle.net/sVKU8/2/

1) I assume this first part is easy - Is there a way to update the parent label class to automatically have it's width set based on the total width of the two child <div>s so the border only wraps around the green and red <div>s? I thought setting width: auto was supposed to do that, but my CSS skills are apparently lacking.

2) What I'd like to accomplish next would be to remove the width attribute from my label-text class and have the width set (or grow automatically, if possible) whenever I apply text to that <div> via JavaScript without text wrapping (i.e. keeping the original height of the label class).

I wasn't sure if I needed to try to calculate the width based on the actual text, or if there is a way to just apply the text with a width setting that will allow it to grow.

Any input or suggestions would be greatly appreciated!

Answer

Yann Chabot picture Yann Chabot · Apr 16, 2013

Add this property to your css :

 .based-on-text{
   display: inline-block;
 }

This way, the div will act like a block but will have exactly the width it needs instead of taking the whole parent level width !