tags:

views:

117

answers:

6

The following code:

<div>
    <img src="" style="float: left;">
    <p>Lorem Ipsum...</p>
</div>

Renders a div container with text, and a floated image on the left. Great. The text included therein also expands the div as much as it can while maintaining the text in a single line (unless otherwise writ). However, with a floated image, the width of the div container does not expand as much as it can, and prematurely line-breaks the text based on the width of the image.

That is, if the floated image is 200 pixels wide, "200 pixels" of text on the right end of the div will all be bumped to the next line. It's as though the DIV container doesn't see the extra text, and sets the dynamic div width too short!

... which, I do realize, is by design, simply because the image is "floated", and is not a block/inline element. (At least, I think I worded that correctly...?)

So, how can I achieve what I want without resorting to (ick...) tables?

A: 

Float the wrapping div to the left as well and it'll wrap the content correctly:

<div style="float: left;">
    <img src="" style="float: left;">
    <p>Lorem Ipsum...</p>
</div>

This is not a perfect solution as floating the wrapping div has obvious side-effects, but it's a sure-fire way of ensuring that a div wraps floated content correctly.

If floating the div gives you any problems you can wrap it in another div which should resolve the issue.

Chris Pebble
A: 

Fails cause float:left requires explicity width

A: 

There is a number of things that can be going on here. When I put your code inside of the body tags of a HTML page with no other code it works fine. This could be because of your page type definition. Mine is:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" >

It also could be because you have a containing that is forcing this div to become shorter. The only way to be sure you solved the issue is to force your area to be of a specific width by setting it's width style. Changing the Div tag your code is in to have a style of float:left most likely does not solve your problem. I checked it just to be sure myself and it didn't produce the results you desired.

RandomBen
A: 

Aside from floating the containing div, you can also add a "width: 100%; overflow: hidden;" style to the containing div. This will force it to expand to contain the floated div. See here for more discussion.

technophile
+1  A: 

Floated elements are removed from the flow of the page and will not cause the enclosing elements to expand.

Take a look here. That tutorial talks about enclosing floated elements by using the overflow property.

Vivin Paliath
A: 

You should also make sure that the element displays as block:

img#my_element {display:block;}
Joseph Silvashy