CSS Float

Wednesday, March 28, 2012

tags CSS

The CSS float property allows a developer to incorporate table-like columns in an HTML layout without the use of tables. With CSS float, an element can be pushed to the left or right, allowing other elements to wrap around it. Floated elements remain a part of the flow of the web page, unlike elements that use absolute positioning. Absolutely positioned page elements are removed from the flow of the webpage.

Elements float horizontally (right or left) and not vertically (up or down). When an element has been specified to float, it will move to the left or right as much as it can. The elements after the floating element will flow around it. This is very similar to what you would see on a magazine page. Values for the float property are left, right, none, and inherit. Most of the time, you will specify the right and left values.

img {float:left;}

Here is a typical example on how you would float an image to the left and allow text to flow around it.

image float Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

Clear Property

Elements after the floating element will flow around it. To avoid this, use the clear property. Possible values are left, right, both, none, and inherit. For example, if you wanted to display text on the page after two elements that have been floated, and you do not want the text to flow around the floated elements, you can specify that the next element be styled with clear:both. This way, the next element will clear both elements and not flow around them.

p.clear {clear:both;}

You can then assign this class to a paragraph after one or more elements that have been floated. The paragraph will clear the previous element and not flow around it.

Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

HTML CSS: The Complete Reference CSS: The Missing Manual HTML CSS and JavaScript Editor