New Posts

Tuesday, April 26, 2011

Floating 102

Sop what interesting things can we do with float?

Lets look at a few examples:

Images in Text



When you have a section with text, and you want to have an image in it, you may need to have the text wrap around it so as to not break up the text. By default images will simply break up the text if placed inside, or just sit on top of it if placed before it.

cover


If we want to have the text wrap around the image we need to float it to one side.

CSS



img{
float:left;
}




Here it is in action:



What happens when we have several images to float.

If the are side by side in the html, they'll continue to float left like below:



If would like the to simply drop below eahc other and have the text wrap around them where they end, we simply need to add a clear:float property to out image CSS.

CSS



img{
float:left;
clear:both;
}




It will look like this:




So floats give us nice layout options with images, but what else can it do for us?

Columns



Usually floating is used to create columns in a layout, as you can place divs side by side and fill them with content. Lets say we want a 3 column layout like a newspaper.
Unlike tables, there is no way yet to make floated divs be as high as each other, they'll be as high as the need to be to accommodate their content. As we've seen in previous entries if there's anything floated inside them extra steps need to be taken to make the div correctly wrap around its contents, however in all cases once its wrapped around, it will only be as high as the content requires.

To create the column layout we need to fake the height of the divs, to the observer it will look like they extend down, but in reality the stop where their content ends.

For our 3 column layout here's our basic HTML.

HTML


<div id="wrapper">

<div id="column1">

<h4>Column1</h4>

<p>Content</p>

</div>

<div id="column2">

<h4>Column2</h4>

<p>Content</p>

</div>

<div id="column3">

<h4>Column3</h4>

<p>Content</p>

</div>

</div>




Here's our CSS:

CSS



#wrapper{
width:402px;
background-color:#686868;
color:#DEDEDE;
overflow:hidden;
}

p{
margin:4px;
}

h4{
text-align:center;
}

#column1{
float:left;
width:120px;
}

#column2{
float:left;
background-color:#dedefe;
width:160px;
color:#686868;
}

#column3{
float:left;
width:120px;
}




See it in action:



As you can see the columns appear to match heights, however, if we add a border to the columns on the outside (column 1 and 3) you'll notice they end where their content ends, the rest is an optical illusion caused by the wrapper's background which is gray.

This works for 2 or 3 columns in much the same way, if you need to have more columns then it gets much more complex. We'll talk about multi column layouts in a future article. For now know you can do this for up to 3 columns.

No comments:

Post a Comment