How to get div to resize to width of contents?
I have the following code:
Code:
<div style="background-color: Blue;">Line 1</div>
<div>Line 2</div>
What style information would I add to the first div so that the blue background is only as wide as needed for the text?
Currently, the div is expanding to the full width of the browser window.
Thanks.
Re: How to get div to resize to width of contents?
then you want a span tag...
Code:
<span style="background-color: Blue;">Line 1</span>
<div>Line 2</div>
or
Code:
<div><span style="background-color: Blue;">Line 1</span></div>
<div>Line 2</div>
depending on your needs....
-tg
Re: How to get div to resize to width of contents?
This is due to elements having either block (div) or inline (span) display properties by default. Relevant reading.
Re: How to get div to resize to width of contents?
That doesn't quite work because if the content in the span extends multiple lines (see example code below), it doesn't render correctly. Problem 1 is that there is a visible gap between the lines and Problem 2 is that the background is not a square. It wants to fit tight around the text. I want a solid box around the content. It seems like span is not what I'm looking for.
Code:
<span style="background-color: Blue;">Line 1<br />Line 1a</span>
<div>Line 2</div>
Re: How to get div to resize to width of contents?
I think I'm getting close. The following code almost works. I have the div fitting the contents correctly, but Line 2 is not going underneath the Line 1, it is floating to the right. How do I modify this to get Line 2 to be underneath Line 1?
Code:
<div style="background-color: Blue; white-space: nowrap; float: left;">Line 1<br />Line 1a</div>
<div>Line 2</div>
Re: How to get div to resize to width of contents?
well, had you mentioned that right from the start, you would have gotten a more appropriate response.
Line 2 isn't floating to the right... it's rendered to the right, line 1 is floated to the left... it's like the drop case letter in older books, where the first letter is illustrated... it's "floating" to the left, allowing the text to flow around it...
Anyways... I'm not sure the float is appropriate anyways... what you really want to be manipulating is the width... but since div tags are block elements... you need to know what width you want...
remove the float and try margin:auto ... that might do it... not sure... I'm not used to dealing with flexible width divs...
-tg
Re: How to get div to resize to width of contents?