Float

Nesting and Floating Elements
To make our page content appear the way we want, and to make the best use of screen space, we can nest and float XHTML elements.

  • Nesting merely refers to placing elements inside other elements.
  • As in real life, smaller boxes can be nested into larger boxes.  We will use this frequently when laying out our web page.
  • Floating in XHTML refers to causing elements, such as <div> containers, to stay to the right or left side of the page, while other elements appear to their side, rather than just above and below.

Example: Nesting <div> Elements
nesting-divHere we’ve placed a box (yellow) inside another box (blue), which is inside a parent box (green).

The Need for Floating Elements
Up to now, the elements we created in our documents were “stacked” vertically.  Once we closed an element, the following element appeared directly below it:
stack-divHow do we use the remaining horizontal space on the page?
A common method is to use the float property.

Divs are block-level elements: this means they force a line break after they close. The float property alters the natural document flow of a web page.

The float Property
The float property moves an element as far as possible to the left or right, allowing the following content to wrap around it. Floats are one of the primary tools of modern CSS-based web design, used to create a multicolumn layouts, navigation toolbars from lists, and table-like alignment without tables.

float
Values: left | right | none | inherit
Default: none
Applies to: all elements
float-property

Here we created a separate class to float an element to the left side of the page and applied the class to both div containers.
float-noteText with Floated Elements
float-textText placed into the document will use the available space alongside the floated elements.  When it runs out of space, it will wrap to the next empty line and continue normally.
clear-noteClearing the Float
clear-float
We could have applied the clearing class directly to the content element instead – in this case, the <p> element for the third paragraph.  But by using a separate <div> to clear the float, our markup is a little easier to read and understand.

Floating Right and Leftfloat-rt-ltWe can also float elements to both the right and left sides of the page.  Subsequent content will then fill the available space between.


Applying floats to layouts
We can use CSS to float elements to the left or to the right.

A Two-column Layout
A Two-column Layout
The markup for two column layout
The markup for two column layout