How to get main div container to align to centre?

Viewed 242801

I have always been wondering how other people get to align to the centre the main div container as the only way I manage so far is adding to the css file the following:

*{
padding:auto;
margin:auto;
text-align:centre;
}

I have seen other pages using: *{padding:0px;margin:0px} but I can't see where or what do they do to centralise the main container.

Could anybody explain how?

Code example:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=windows-1252" http-equiv="Content-Type" />
<title>This is the main container</title>
<style type="text/css">
*{
padding:auto;
margin:auto;
text-align:center;
}
</style>
</head>
<body>
<div style="width:400px;background-color:#66FFFF;display:block;height:400px;">
<b>This is the main container.</b>
</div>
</body>
</html>

Could anybody explain how do they do it in the following page?

http://www.csszengarden.com/?cssfile=/179/179.css&page=4

4 Answers

Do not use the * selector as that will apply to all elements on the page. Suppose you have a structure like this:

...
<body>
    <div id="content">
        <b>This is the main container.</b>
    </div>
</body>
</html>

You can then center the #content div using:

#content {
    width: 400px;
    margin: 0 auto;
    background-color: #66ffff;
}

Don't know what you've seen elsewhere but this is the way to go. The * { margin: 0; padding: 0; } snippet you've seen is for resetting browser's default definitions for all browsers to make your site behave similarly on all browsers, this has nothing to do with centering the main container.

Most browsers apply a default margin and padding to some elements which usually isn't consistent with other browsers' implementations. This is why it is often considered smart to use this kind of 'resetting'. The reset snippet you presented is the most simplest of reset stylesheets, you can read more about the subject here:

You can text-align: center the body to center the container. Then text-align: left the container to get all the text, etc. to align left.

I would omit the * { text-align:center } declaration, as it sets center alignment for all elements.

Usually with a fixed width container margin: 0 auto should be enough

Related