Recipe 1.14. Using Floats with Images


Problem

You want to place an image on the left or the right side with text wrapping around the image instead of appearing above or below the image (see Figure 1-35).

Figure 1-35. Images do not wrap around the text by default


Solution

First create class selectors for the images:

.leftFloat {  float: left } .rightFloat {  float: right }

Then add the class selector to the markup and see how it works in Figure 1-36:

<img src="/books/3/27/1/html/2/csscookbook.gif"  alt="cover" /> <p>This is the book cover for the <em>CSS Cookbook</em>.</p> <img src="/books/3/27/1/html/2/csscookbook.gif"  alt="cover" /> <p>This is the book cover for the <em>CSS Cookbook</em>.</p>

Discussion

In the times before there were any compliant standards, designers used the align attribute with the img element to move images to the side with text wrapping. W3C deprecated align and now recommends using float instead.

Floats can be used with elements other than images to shift an item left or right within its current place. In Figure 1-36, the second image overlaps with the paragraph referencing the first image. This looks confusing and needs to be fixed. To work around that, use clear:

p {  clear: left; }  

Figure 1-36. With float, the text wraps around the images


The clear property tells the paragraph to appear after the end of the image flow. At the second img, the clear properties push the image down to the first line after the previous ends. Instead of lining up with the second p element, the image waits for a new line before showing up.

See Also

W3C 2.1 specification on floats at http://www.w3.org/TR/CSS21/visuren.html#floats; Chapter 9 provides three recipes on using float with page columns; and Eric Meyer's CSS/edge covers floats at http://meyerweb.com/eric/css/edge/.




CSS Cookbook
CSS Cookbook, 2nd Edition
ISBN: 0596527411
EAN: 2147483647
Year: 2006
Pages: 235

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net