Reply to comment
css floats - how, what,why
Submitted by Jonathan Wagener on Tue, 09/02/2008 - 23:17 Send to friendPrinter-friendly versionI know that when i started working with CSS a few years ago the thing that got me stuck were floats. I could never get them right. :)
So i thought that maybe someone might benefit from me chatting a little about css floats. so here they are. this is just a very basic tutorial, if you want to know more or add to this please feel free to leave a little comment.
So what are floats? Basically, a float is similar to a table layout - but instead of creating a table to display two pieces of content (we'll call these blocks for now) next to each other, you would instead create two float divs. I will now demonstrate how you do this.
lets set the scene quick, you have a blog, like this one, where you need to have a content area and you would also need a little sidebar to display some of the latest posts as well as some links to your friends blogs as well.
How would you normally do this? Well, i usually would've created a little table and there we go, i'm happy (for a little while until i need to change a few things). In my personal opinion creating a table is the lazy way (i am a big advocate on css only design) and will cause you problems in the long run - believe me, ive been there and done that :).
So what other options do you have in your toolbox that might be able to do a better job, i suggest using a css float, as it is really easy to use and will save you time in the long run when you may need to do updates.
So lets start:
.content_block
{
float: left;
width: 300px;
height: auto;
margin: 5px;
padding: 5px;
border: 1px #000 solid;
}
.sidebar
{
float: left;
width: 150px;
height: auto;
margin: 5px;
padding: 5px;
border: 1px #000 solid;
}
the above code sample will create two floating blocks - these will sit next to each other (unless one is too wide, where the one float will site under the other).
to use the above css code, you just create two divs:
some sample contentBlogroll
and that is basically how you create a css float (well we created two). this shows how easy it is to make it work.
one more thing, making the float is easy, but the clearing part is what most people forget. in order to put ordinary elements under the floats you have to clear the float or else the element under them will site underneath the float.
.clear
{
clear: both;
height: 0;
}
you just add that div before you want to add an ordinary element underneath a float. Please note that you must not add these underneath every float, only under groups, or every float will be on a new line.
i hope this helps someone.
