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.
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]