NEWSFLASH!

Hi guys,

Hopefully you read some fun and helpful stuff here. This blog is mainly aimed at the novice, mediocre and pretending to be advanced css student. If you have comments, questions or anything don't hesitate to post them. If you are completely new to css, you might want to have a look at a free tutorial of a former student of mine, although it's not a book, it should teach you the basics to give you a head-start in building your very own website.

Any ways enjoy your stay guys,

If it's not here maybe on a new blog somewhere with a decent editor. or if you lads are really generous on a commercial website :)

Cheers!



Cssfreakie



Friday, March 18, 2011

How to center a page using css

Hello everyone,

Today i quickly want to show you how to center a div the good way. Quite often I see people use the <center> tag for this. All i can say is don't. IF you want to know why google, it, but i rather cut the crap and show how to center your page the good way instead of saying why <center> is bad.

It's pretty easy really. First of all we need to wrap every content we have a in a container. We use a div for that because that's what div's are for (containing other elements). We give it a nice #id of wrapper so we can target it from our style sheet. Than we give it a fixed width and by using margin we can center it to the page.

Code:
<style>
div#wrapper{
  width:960px;
  margin:0 auto;
  overflow:hidden;
}
</style>


<body>
<div id="wrapper">
   .... content goes here
</div>
</body>


Some things to pay attention to:

margin: 0 auto;
This tells the wrapper div to have a margin of 0 at the top and bottom, and auto tells it to have a margin set automatically for the left and right side, and that causes it to sit in the middle.
Now this only works, if the wrapper div has been given a width other than 100%. As you probably do or do not know div elements span the whole width unless you tell them otherwise or float them. So if you would not have set a width ( it's 100%) margin:0 auto; wont do a thing since there is no margin to the left and right. Try it out!

Overflow:hidden;
This is a little trick that makes the wrapper div shrink wrap around the inner content. This only works if only a width but not a height is set or vice versa. Now some people use a clearfix for this. But that is wrong in this case. More info on that can be found here. I wrote a short article on it.

Hope this was useful for you guys,
And as always if you have questions, comments or requests for an article feel free to post them.
See you next time,

Cssfreakie

1 comment:

  1. Thank you SO MUCH! I have been looking for hours for a plain language explanation of this.

    ReplyDelete