Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize <div> automatically based on text?

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!

like image 853
lhan Avatar asked Apr 16 '13 21:04

lhan


People also ask

How do I resize a div by content?

Using inline-block property: Use display: inline-block property to set a div size according to its content.

How do I Auto size a div?

The css rule: white-space: nowrap; will prevent your lines wrapping. Set a width of the error div to 100% and it will automatically fill the space available.

How do I make a div fit text?

You can simply use the CSS display property with the value inline-block to make a <div> not larger than its contents (i.e. only expand to as wide as its contents).


1 Answers

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 !

like image 64
Yann Chabot Avatar answered Oct 20 '22 20:10

Yann Chabot