views:

117

answers:

3
<div style="background-color:black">
   <div style="float:right">
       Test message
   </div>
<div>

This will show 'Test message' with white background because the parent div didn't fit the content.

How can make the div fit to the content? (without using table, or display:table since it's not supported in IE)

A: 

A common solution is to put a <br style="clear: both;"> after the floating element to clear the float and cause the parent element to wrap the elements.

<div style="background-color:black">
   <div style="float:right">
       Test message
   </div>
   <br style="clear: both;">
<div>

Apart from the problem, I'd suggest to put the styles in a separate CSS file, if not realised yet.

BalusC
+2  A: 

Sounds like this is the old clearfix issue. This is almost a total necessity when using css and floats for layouts. See http://www.webtoolkit.info/css-clearfix.html for a brief description and fix. Or for a more in depth look, see here http://www.positioniseverything.net/easyclearing.html

TehOne
+3  A: 

You can also do this:

<div style="background-color:black; overflow: auto;">
   <div style="float:right">
       Test message
   </div>
<div>

It's a cleaner way to do the clearfix :)

Nick Craver