FLoating Elements In CSS
Lessons Covered

In CSS you often times find yourself wanting to have some text to the right of an image or even to the left of that image. You try the text-align property but it doesn't seem to work; so what's the solution ?


The answer is, the float property.



This property is used to float elements to the left or to the right. After doing this anything that follows will float around the element. So in the case of an image floated to the left, the text that follows will appear to the right of that image. Similarly an image floated to the right, the text that follows will be floated to the left of that image. In the examples below we make an attempt to accomplish placing some text to the right of an image.


Image without floating property ( Normal )

This is how the image and text would appear normally:

The code:

<img src="images/rose.jpg" title="A rose" alt="Rose" />

<p> This is an image of a rose. </p>


The result:

Rose

This is an image of a rose.


Notice how the paragraph of text, "This is an image of a rose." appears beneath the image ? There is no difference when the text-align property is applied.




Image with floating property

Now, the difference when the float property is applied:

The code:

<img src="images/rose.jpg" title="A rose" alt="Rose" style="float: left;" />

<p> This is an image of a rose. </p>


The result:

Rose

This is an image of a rose.


The text now appears to the right of the rose which was floated left.



The Clear Property

The clear property is used closely with the float property to break out of the float. Remember when the image is floated to the left then the paragraph of text appears to the right and vice versa. If you don't want the elements which follow to appear next to the floated element then you use this property. The values are both, left and right. Look at the example below.

The code:

<img src="images/rose.jpg" title="A rose" alt="Rose" style="float: left;" />

<p style="clear: both;"> This is an image of a rose. </p>


The result:

Rose

This is an image of a rose.


Now in this example you can see we still have the float property applied but instead of the text being displayed to the right of the image it is displayed at the bottom. This was accomplished by the value both.


    Previous Lesson Previous Lesson - Margin and Padding                            Back To Home Next Lesson