How to make <body> in the center of a web page?

margin: 0 autodoes not work when 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>
Run codeHide result
+4
source share
3 answers

margin: 0 auto;only works when a property widthor max-widthcss is applied . You set widthon the body, but margin: 0 autoon #headerthat which is wrong. Move yours widthor max-widthin #header.

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>
Run codeHide result
+1
source

you cannot set the width for the body

set the box and padding for your body and set the div for your title,

body 
{
   margin:0;
   padding:0;
}
#header
{
   width:960px;
   height:100px;
   background-color:Green;
   margin:0 auto;
}
+1
source

:

*{margin:0 auto}

0

All Articles