16

Possible Duplicate:
Make CSS Div Width Equal To Contents

I am trying to make a chat like application but now I ran acros a little bug of some sort.

I have a div with a max-width set to 350px. But when I put the following text in it:

dddddddddddd ddddddddddd dddddddddd dddddddddd

It will add new lines at every space but the width of the div will stay at 100px. I made a little example in jsFiddle here:

http://jsfiddle.net/5t2hm/12/

As you can see the width of the yellow box is 100px while I want it to shrink to the width of the text. I also tried to fix it with using a element but the yellow box remains the same.

Bascily I want it to look like the third box while retaining the max-width part.

Does someone got any idea how the yellow box will shrink to the width of the text?

Community
  • 1
  • 1
Dirk-Jan
  • 1,109
  • 10
  • 21
  • But in fiddle have width is 100px!. you change 100px to 350px. – Selvamani Oct 01 '12 at 11:48
  • true. I made the example a little smaller but the problem still remains. I also tried the other page as mentioned by Álvaro G. Vicario. But I am still having issues. – Dirk-Jan Oct 01 '12 at 11:50

3 Answers3

2

check this fiddle1 or fiddle2.

Instead of using one div use two div's (or)
one div and one span. I think this is what you want.

Mr_Green
  • 40,727
  • 45
  • 159
  • 271
1

Use para

<p></P>

Demo: fiddle

Selvamani
  • 7,434
  • 4
  • 32
  • 43
  • Not exactly where I was looking for. Basicly I want it to look like the third box in this fiddle: http://jsfiddle.net/5t2hm/12/ But the third box doesn´t have a max-width set but that is needed for the project. – Dirk-Jan Oct 01 '12 at 12:08
  • yeah i am ready to help you. But i did not understood. Can you please insert image here.. – Selvamani Oct 01 '12 at 12:15
  • I am sorry. I rechecked your answer and indeed the behavior of the div will change if I add the

    tags. However this is not possible because its supposed to render human input and then I need to check for a way that it will add

    tags when a certain sentance is too long. However with the tags it rendered correctly! Thanks for that!

    – Dirk-Jan Oct 01 '12 at 12:25
1

The default width of a DIV is 100%, so max-width is just capping that in your fiddle - it won't consider the width of the content.

To shrink your DIV to its content you'd need display: inline-block; or float:left; width:auto;.

http://robertnyman.com/2010/02/24/css-display-inline-block-why-it-rocks-and-why-it-sucks/

Lee Kowalkowski
  • 11,591
  • 3
  • 40
  • 46