Using Float

The most common use for the float attribute is to position an image to the left or right in a page and have the rest of the text flow around it. This allows you to design pages with a very natural "magazine page" feel that readers will be familiar and comfortable with.

Floating an Image

GlobeIn the example that we have here the globe image has been floated to the right of the page. This accompanying text sits beside the image and there is no overlap. In addition, in order to ensure that the text does not crowd the image, there is a left margin of 15px specfied to keep a comfortable gap.

This is all achieved using a style rule. In this case I have called the rule .imageLeftMargin and it is defined in the main style sheet used on all of these pages. Because the rule is defined in an external style sheet which can be loaded into any page, the rule can be applied to any image simply by specifying that the image has the appropriate class, in this case "imageLeftMargin".

If you are using Firefox to view this page, you can right click and then select view source. Locate the img tag corresponding to the globe (the name of the image is 4.png) and see that it has the expected class. Next, find the link to the style sheet oneColLiqCtrHdr in the <head> of the document and follow the link to see the actual style sheet. Find the relevant rule in the style sheet.

The Style Definition

The definition for the rule is shown here:

.imageLeftMargin {
  	margin-left: 15px;
  	margin-bottom: 10px;
  	border-top-style: none;
  	border-right-style: none;
  	border-bottom-style: none;
  	border-left-style: none;
  	float: right;

Notice the value for the float and various margin attributes. There is a corresponding rule for floating an image to the left and applying a right margin. Write down that rule now, and then check with the style sheet to see if you have it correct.

Floating Other Elements

Notice that it does not have to be only images that are floated.

Not only images, but any block level element such as a div can be floated. This can sometimes be useful to create a sidebar in a page with additional information for the reader.

You can see an example of this on the left, where a div containing text has been floated. If you look at the source for this page, you will see that the element has the imageRightMargin style rule applied, but also has some extra inline style declarations to format the appearance of the div.

Doing This Without Styles

It is possible to get the same basic effect using only HTML attributes, without resorting to styles. This was shown previously here.

Whilst this approach is sometimes OK for simple layouts, it does not give all the flexibility of using styles. In particular, you do not have separate control over the left and right margins, and nor can you use the clear attribute. Generally, I would recommend using style rules to position elements in a page.

Back Return to the main CSS Position page.