Margin: 0 auto not centering?

I tried the following code in Chrome, Firefox and Safari, but my div is not quite 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;
}

In Chrome, the following appears: alt text

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

What am I doing wrong?

+3
source share
5 answers

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

body { margin: 0px; }

You might want to use CSS reset .


This should look fine if your window is larger. In the screenshot, I like this:

mug

+15
source

The window is too narrow. Automatic alignment of center elements in the available space, if the space is narrower than the element, then it is aligned to the left.

, body ( , Chrome), div, 400 , , , .

+2

. . , .

. , , , -, .

, , , , , IE7-9 FF chrome.

.submitArea .actButton  {margin-right: auto !important; margin-left: auto !important; display: block;}
@media screen and (-webkit-min-device-pixel-ratio:0) { .submitArea .actButton  {display: inline-block !important;}}  /* chrome hack - needs width for buttons to center */
+1

css.

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

Try to do this as css for your .center class:

.center {width: 400 pixels; Margin to the left: auto; Margin to the right: auto; border: 5px solid black; }

-3
source

Source: https://habr.com/ru/post/1772285/


All Articles