Ronnie
Ronnie

Reputation: 1073

Centering entire page with CSS

I am attempting to center my entire page using only CSS and it is proving more complicated than i first expected. Currently my code works in IE but not in Firefox which makes a change. The page can be seen here. Below is the code portion involved:

#wrap {
    width: 960px;
    margin: 0 auto;
    padding: 6px;
    background: #FFFFFF;
}

The structure of my HTML is:

<body>
<div id="wrap">
    Gubbins in here.
</div>
</body>

It seems that in Firefox everything following the wrap div is be created outside of it. This is problem is resolved if i add a 'float: left' to the wrap div but then obviously everything floats left rather than center.

Any help would be greatly appreciated.

Upvotes: 0

Views: 6159

Answers (3)

codeinthehole
codeinthehole

Reputation: 9026

If you know the width of your page - and it's fixed, you can use the following methodology.

  • Contain your page content with a div (which will act as a wrapper)
  • Give this 'wrapper' div a width of 'W'
  • Position the wrapper div using 'left: 50%;'

now, utilising the fact that it's possible to have a negative margin...

  • Pull back the positioning of the wrapper div using 'margin-left: -(W/2);'

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415820

Use this CSS:

body { text-align:center;}
#wrap {text-align:left; margin: 0 auto; width:960px;}

Then, let's examine this statement from your question:

everything following the wrap div is be created outside of it

That's kind of the way it works. Don't put anything outside of your wrap div. Think of it as a surrogate body.

Upvotes: 0

John Sheehan
John Sheehan

Reputation: 78124

Change your markup to

<body>
<div id="wrap">
    Gubbins in here.
</div>
</body>

EDIT: Looking at the link, you've already done that. You'll want to either add overflow:auto; to #wrap or add a clearing div at the end just before the closing tag on the wrap div.

Also, on your example page, the wrap div is missing its closing tag.

Upvotes: 5

Related Questions