Need help centering a DIV with CSS

Hey everyone,

I am fairly comfortable with HTML, and even know a decent amount of PHP and Javascript. But sometimes trying to do the simplest things in CSS makes my head spin! (this is one of those times).

I’ve got a “scrolling” header at the top of a page (stays visible even when scrolling), and am trying to center a DIV (which contains opt-in forms) inside that header. It looks good when my browser window is maximized (at 1280x1024 resolution). But when I minimize the browser or check it in other screen resolutions, the “centering” of the opt-in forms are off.

Here is the page…

And here are the CSS includes…

This was really just a quick hack from a “scrolling header” demo I found online, so I must have overlooked something.

Any ideas?

You’ve set a width of 1261px, which will extend off to the right hand side of the window if it’s narrower than that. You don’t need that - block elements always have a default width of 100%, so you don’t need to set a width at all, but if you do, make it 100%.

The standard CSS to center a div (or any block element) is to set the left and right margins to auto. If the top and bottom margins are zero, this will work…

#centeredDiv {
margin: 0 auto;

However, I still don’t completely understand why it doesn’t work in some cases though there are a number of other guys who can help in those situations. If you’re centering inline elements, it’s even easier; text-align: center;

The main reasons why using that method to centre a <div> are:

[list][]<div> takes 100% width unless specified, so will naturally fill the whole available space.
]If <div> has specified width and formatting context means that parent <div> shrink-wraps its children then centering will have no effect.
[*]If width of <div> is greater than available space, it will be left aligned and disappear off the right.[/list]

Hey guys…

Thanks for the suggestions. Been playing around with it some more and have it working pretty well now, for the most part…

The only inconsistency now is with IE7… which adds an extra (unnecessary) scrollbar next to the header. Plug one leak and another one pops up, lol.