Up to now, the only sort of content flow you have seen is top to bottom.
Every block element you have used either nests inside another block element or stacks top to bottom in the order it appears in the document. There was no way to place blocks side by side.
The float property was originally introduced to allow text to flow around image elements – thus eliminating a lot of white space and making for more esthetically pleasing documents.
The float property can take the values of left, right or none. By default, all HTML elements have float set to none.
Consider the following code snippet which places an image on the left side of some text:
Consider the same image to which float:left has been applied:
A similar effect is obtained when float:right is applied to the image:
While it seems to work well, it has problems that become evident for anything but the simplest of layouts.
Consider the following styling:
Applied to the following HTML code:
<p id="paragraph1" class="border yellow-bg"> <img src="26-dog.jpg" class="float-left"> To make the problem stand out, each paragraph is uniquely identified and has a border and background colour styling applied.</p> <p id="paragraph2" class="border lime-bg"> It should be immediately obvious that the image is no longer contained within the paragraph it was embedded.</p> <p id="paragraph3" class="border orange-bg"> In fact, it is spilling over several paragraph blocks, as if it were laid on top of them.</p> <p id="paragraph4" class="border cyan-bg"> But it doesn't cover up the words or content. </p>
Gives the following results:
In the next tutorial, we will learn why this happens and what we can do about it.
- The float can be used to position an element to the left or right side of a page.
- Content (usually text) will flow around the floated element.
The best way to learn is to play around with what you have learned.
Try using float. The easiest and most visual way is to use small images, although you can also create coloured boxes and use those.
Apply it to a single HTML element, to multiple HTML elements. What happens when you nest floated elements?
The idea is to get a feel for how float behaves when you use it.