Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase div width according to the text inside it?

I have a div that users input text in it. But I want to increase it's width according to it's text, until a max of 50% of the screen. My CSS code:

.messages {
   max-width:50%;
   min-width:150px;
   background: #ffeec0;
   padding:2px;
   margin:3px;
   -webkit-border-radius: 2px;
   border-radius: 2px;
   border:1px solid #ffdd7c;
}

Result: enter image description here

There's a lot of space after the "555" message, I want this size only if the user inputs some text like:

enter image description here

So, how can I increase the div's width dinamically, depending on the text size?

like image 201
Edie Johnny Avatar asked Sep 21 '14 07:09

Edie Johnny


People also ask

How do I change the width of a div in text?

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

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.

How do I make div width auto adjust?

Using width, max-width and margin: auto; Then, you can set the margins to auto, to horizontally center the element within its container. The element will take up the specified width, and the remaining space will be split equally between the two margins: This <div> element has a width of 500px, and margin set to auto.


2 Answers

There are many ways to achieve this, but IMHO the cleanest is the following. Your problem is that the boxes are "greedy" and will try to expand to the available width.

To prevent this, you can:

  • Make it "float: left;"
  • But also "clear: left;" to prevent additional "left floating" elements to use the available space on the right.

The CSS becomes:

.messages {
   max-width:50%;
   min-width:150px;
   background: #ffeec0;
   padding:2px;
   margin:3px;
   border-radius: 2px;
   border:1px solid #ffdd7c;
   float:  left;
   clear: left;
}

I provided full code and additional explanation (on mouseover) on the Liveweave here: http://liveweave.com/DFCZFj

LiveWeave screenshot

like image 164
Pivert Avatar answered Oct 30 '22 07:10

Pivert


Try changing display type of the div to table.

Example Here

.messages {
   display: table;
   max-width: 50%;
   min-width: 150px;
   /* other declarations omitted due to brevity */
}
like image 25
Hashem Qolami Avatar answered Oct 30 '22 07:10

Hashem Qolami