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.
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:
How 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.
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.
Text with Floated Elements
Text 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.
Clearing the 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.
Applying floats to layouts
We can use CSS to float elements to the left or to the right.