Controlling Layout with CSS

By default, HTML <div> sections will fill 100% of the web page width, and stack up one on top of the other. It is highly unlikely that this is how we want our page elements to be arranged; chances are we want some sections arranged side by side, and using various widths. For example we might want to have a main content area with a menu down the left-hand side. Thankfully CSS makes this a simple task. The first step is to understand the float property.

The CSS float property

The float property tells HTML elements how to arrange themselves in relation to the other divs around them. We can specify one of two values for the float property - left or right. If we tell a <div> to float to the left, then it will shift itself as far left on the line as it can go before bumping into another <div> section. If we tell an element to float to the right it will shift as far right as it can.

Let's take a look at a working example; this will give us a good visualization of how floating works. We'll begin by defining three areas for our web page:

<div id="header">This is the page header</div>
<div id="menu">Menu links goes in here</div>
<div id="content">And finally the page content in here</div>

Now, what we want to do is to have the header take up the whole of the top row, with the menu and content underneath, arranged side by side. To do this we would use the following CSS (the header section doesn't require any CSS):

#menu {
	float: left;

#content {
	float: left;

This produces the following result. Notice that I've colored the individual sections for clarity:

This is the page header
And finally the page content in here

Here we have floated both the menu and the content sections over to the left of the page, so that they stack up against one another. It is important to realize that the order we put our divs in the HTML determines the order they are placed in our final page. Because we coded the menu first in the HTML (see above), it is placed first, and then the content section is stacked up against it. If we had put the content section first the opposite would have happened.

On the next page we see how to gain even more control over our HTML elements by specifying widths for them, and how to force an element to sit below all other elements.