21

My question is simple:

Can you stop a div from auto-stretching to the width of its containing element and have it only stretch horizontally as much as the content inside it forces?

Kind of like the default vertical behavior of divs but applied horizontally. Is this possible?

Sony packman
  • 810
  • 2
  • 10
  • 21

2 Answers2

31

You'd have to set the display property to inline-block

<div style="display: inline-block">Text</div>
Ross McLellan
  • 1,872
  • 1
  • 15
  • 19
5

Actually, display:inline will have better browser support, but may not achieve the results you want, it will keep the div in line with the content, a la <span>.

There's two types of elements: block, and inline. Block elements stretch to width and break the line. Inline stretches to content and stays inline. (!)

display:inline-block is getting better support, but the older browsers won't do it.

Ben
  • 54,723
  • 49
  • 178
  • 224