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:
There's a lot of space after the "555" message, I want this size only if the user inputs some text like:
So, how can I increase the div's width dinamically, depending on the text size?
Using inline-block property: Use display: inline-block property to set a div size according to its content.
Syntax: width: length|percentage|auto|initial|inherit; Property Values: width: auto; It is used to set width property to its default value.
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.
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:
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
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 */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With