There are literally hundreds, if not thousands, of tutorials to be found on the internet that describe how to center a website. It’s not that hard at all, so I decided to write my own, rather short, tutorial on this topic. Theoretically, it can be done with under 10 lines of code, so this will be an easy one.
This tutorial consists out of two parts, some HTML and some CSS. Off course you need to link the CSS to the HTML, but that’s not what I’m going to cover in this tutorial. There are lots of ways to do that, Google is your friend. Let’s look at the code.
HTML:
<div id="wrapper"> This content will be centered. </div>
CSS:
#wrapper {
margin: 0 auto;
width: 150px;
}
The CSS displayed above is just for centering, no further markup will be applied.
Explaining the code
Let’s take a closer look at the code. We’ll start with the HTML, the first line of the HTML to be specific. Here we are creating a div that’s been given the id: wrapper. The id is what we’re going to use in the CSS to address the correct div. Whatever is inside the div, a single line of text or a entire website, will be centered.
HTML:
<div id="wrapper"> This content will be centered. </div>
The CSS will give properties to this div, we’re looking to the second and third line of code to be specific. Theses line are the real properties that will be applied to the div, the other lines are used to address the correct div. But that’s basic CSS, you should read some basic tutorials on that topic if you’re having trouble with it.
With margin: 0 auto; we give a automatic margin to the left and right side of the div, that will force the div to stay in the center of it’s container. And because we are using this div as a container for the entire website, the entire website will be centered.
CSS:
#wrapper {
margin: 0 auto;
width: 150px;
}
I’ve added a fixed width to the div, to make the effect more obvious. When there is no width set for a div, it will use 100% of it’s container. Without any other code around it, the div will maximize itself to the full page and can therefor not be centered.
That’s it! When you link the CSS code to the HTML, the div with the id wrapper (and everything inside it) will be centered.
It really is that easy!
Yes, it is that easy. It works in all browsers that are worth supporting, so why bother working it out in any other way? Leave all the other tutorials behind, keep it simple!
Related posts: