This is the last post in the "Introduction to CSS Positioning" series. We look at two new properties that will help us create layouts with columns: "float" and "clear".
You can download the files used in this exercise here.The Float Property
Floats take a bit of getting used to. They are counter-intuitive and can be confusing. In this post we will apply them without delving too much into the theory behind them – lets learn by doing.
The float property makes an element move as far as it can to the right or left side of whatever contains it.
So lets try it out. You may think the thing to do is to make the green box "float" to the right – but actually, we are going to float both the blue and the green boxes to the left, and the result will be two perfect columns. Wait and see.
First – we float the blue box to the left like this:
.bluebox {width:195px;
background-color:#1E90FF;
padding:5px;
margin:10px;
float:left;
}
Let's see what effect his has on the layout:

Yikes! That's not quite what we had in mind. The green box has shifted up, but it has slipped in behind the blue box. Why is that?
When you float a page element, it acts as though it has been partially "lifted" out of the html box model, and this changes the way other page elements interact with it. In this case the green box behaves as though the blue box is no longer there – it moves to the left just as it would if you had deleted the blue box. (Notice that the text inside the green box still moves down to make space for the blue box.)
So obviously there is more work to be done here before we have our nicely floating column layout. To get the green box to sit next to the blue box, we will float it as well. In this example, we will float it left by adding the same property to the .greenbox style rule:
.greenbox {
width:195px;
background-color:#009966;
padding:5px;
margin:10px;
float:left;
}
The "container" div tag now behaves as though the .greenbox and .bluebox div tags are no longer inside it, and has snapped up. We would like it to stretch down to surround those two div tags.
The simplest way to do this, is to add one last, empty div tag below the .greenbox div tag, and use CSS to style this new div tag so that the float attributes of the two div tags above it is "cleared". Since this last div tag does not have a "float" attribute, the .container div tag will stretch down to contain it, and so also contain any div tags that appear above it in the HTML structure.
So – in the .html file, we add the following div tag below the .greenbox div, but still inside the .container div:
And in the CSS, the following rule:
.stretch{
clear:both;
}
And that should result in a layout like this:

Tags: clear · CSS Positioning · floatNo Comments


0 responses so far ↓
Like gas stations in rural Texas after 10 pm, comments are closed.