4

margin: 0 auto not working when the body width is set. why?

body {
    width: 960px;
}
#header {
    height: 100px;
    background-color: Green;
    margin: 0 auto;
}
<html>
   <head>
       <title>Menu</title>
       <link rel="Stylesheet" type="text/css" href="menu.css" />
   </head>
   <body>
    <div id="header">
        
    </div>
    </body>
</html>
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
Sabari
  • 51
  • 8

3 Answers3

1

you cannot set width for body

set margin and padding for your body, and set with for your header div,

body 
{
   margin:0;
   padding:0;
}
#header
{
   width:960px;
   height:100px;
   background-color:Green;
   margin:0 auto;
}
danilonet
  • 1,757
  • 16
  • 33
1

margin: 0 auto; works only when applied with width or max-width css property. You have set width on body while margin: 0 auto on #header which is wrong. Move your width or max-width to #header as well.

body {
    margin: 0;
}
#header {
    height: 100px;
    margin: 0 auto;
    background-color: #0f0;
    max-width: 500px; // you can set width if you don't need responsive page
}
<html>
   <head>
       <title>Menu</title>
       <link rel="Stylesheet" type="text/css" href="menu.css" />
   </head>
   <body>
    <div id="header">
        
    </div>
    </body>
</html>
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
0

try this code:

*{margin:0 auto}