Oct
29

Centering the page

You can centre your content in the middle of the page by setting it’s ‘left’ property to 50% and then setting the ‘margin-left’ to minus half of the content’s width. Taking the example of a rectangle:

#content{
position:relative;
width:500px;
height:400px;
left:50%;
margin-left:-250px;
}

Here we’ve moved the rectangle so that its left edge starts exactly in the middle of the page. We then use the margin-left attrribute to move it back to the left by half of the rectangle’s width – leaving it dead in the center.

This effect can also be achieved using only the ‘margin’ attribute and setting this to margin:0 auto; (this has set the top and bottom margin to 0 and the left and right to auto).

Unfortunately this won’t work in IE6 or earlier but we can fix this by also adding the attribute text-align:center; to the rectangle’s parent element (this could be ‘body’, for example). This will also have the effect of centering all of the text inside our rectangle so don’t forget to set ‘text-align’ back to left if that’s how your text is meant to be.

Leave a comment

Sponsored links