views:

171

answers:

2

HI all,

I have allways 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 cant 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"&gt;
<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&amp;page=4

Thanks

+4  A: 

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:

Tatu Ulmanen
+1 for your answer..
c0mrade
Is is not good practice to apply *{padding:0px;margin:0px;}, to make it more cross browser compatible?
Cesar Lopez
@Cesar Lopes, in my opinion it is, but there seems to be people who think otherwise. But I'd say go ahead with it.
Tatu Ulmanen
@Tatu Ulmanen, Thank you for your great question.
Cesar Lopez
+1  A: 

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

Juraj Blahunka