Using floats in CSS
Floating images
One of the most common things to do with an image is to make it float inline with text. This can be done easily using the align attribute.
<img src="image" align="left" alt="Image description" />
Text text text …
The three most useful alignments are left, right (which align the image inline with the text in the respected position) and middle (which aligns the timage in the middle of the text).
Using CSS floats
Div
tags can also be useful for aligning content when they are used with the float CSS property.
<div id="right">Text floated on the right …</div>
Text text text text text text …
We need to first float the div
tag to the right, but we can also define a width to keep the style constant.
#right
{
float: right;
width: 100px;
}
This method gives us a good way to put content on either the left or the right in a neat box that varies in height depending on the length of the content. Again the most useful floats are left and right which make the content appear in the respective direction.
Float rendering
Below are a few things to note when using floats:
- Block level elements appear like inline elements when used with floats (will wrap to the content)
- When using multiple floats sometimes using a spacer div (
<div style="clear:both" />
) prevents text wrapping aroun the float - Using spacers makes sure that the content flow is not interrupted when the browser window is resized
- Using either fluid or fixed widths can help to keep the presentation consistent