tags:

views:

45

answers:

3

I've tried the following code in Chrome, Firefox, and Safari, but my div isn't quite being centered.

HTML:

<!DOCTYPE html> 
<html> 
<head> 
    <link href="custom.css" media="screen" rel="stylesheet" type="text/css" />
</head> 
<body>  
    <div class="center">Hello!</div>
</body> 
</html>

custom.css:

.center {
  width: 400px;
  margin: 0 auto;
  border: 5px solid black;
}

This produces the following in Chrome: alt text

and you can see that the left margin is bigger than the right margin.

What am I doing wrong?

A: 

Try this as css for your .center class:

.center { width: 400px; margin-left:auto; margin-right:auto; border: 5px solid black; }

3sdmx
That's basically the same. >.>
Time Machine
+4  A: 

It is because the body has a margin (default for browsers):

body { margin: 0px; }

You might want to use a CSS reset.


It should look normal if your window is bigger. In your screenshot it's like:

mug

Time Machine
+2  A: 

The window is too narrow. Auto margins centre elements in the available space, if the space is narrower than the element, then it becomes left aligned.

So, from left to right you see the padding or margin on the body element (margin in this case as it is Chrome), then the border for the div, then the 400px of width, then the next border, and then the window edge as there isn't any more space to render the body's right margin.

David Dorward