Sabari Sabari - 6 months ago 25
HTML Question

margin 0 auto not working when the body width is set

I'm new Programming. Just started learning. margin 0 auto not working when the body width is set. why???



CSS:
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>




Answer

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>

Comments