Your content centered

2007-07-26

Maybe one of the strangest things in HTML and CSS is the difficulty to get things centered.

Of course there's the
tag, but that's being depricated in the later standards.

The only direct alternative is CSS-es "text-align: center;", but this really only works for text (well, not really, but it doesn't server our purpose).

So then what? There are various ways to achieve it. With and without javascript. Although js is much easier, it makes your website dependent on an extra system (javascript), while a lot of users will disable javascript.

If you search for it you'll find various solutions. The solution I'm using (for this site as well) is the next piece of CSS code for a
that contains a page that's 900px width:
Code: (CSS)

#back {
width: 900px;
margin-left: -440px;
left: 50%;
}

(This also works vertically with margin-top and height.)

The advantages:
- page is centered
- works in IE 6, IE 7, FF 2, Opera 9.2

The disadvantages:
- width of the website has to be known in advance
- if the browser is smaller then the intended width both sides of the page will fall outside of the viewport