Centering div inside body
I have this html:
<body>
<div id="maindiv" class="rounded">
something written
</div>
</body>
with this css:
body {
background-image: url('stjohnhusimages/green gradient.png');
background-repeat: no-repeat;
width:1024px;
height:1375px;
background-size: cover;
text-align:center;
}
#maindiv {
width:900px;
height:1275px;
margin-left: auto;
margin-right: auto;
margin-top: 40px;
background-color:#404853;
}
but the main div is still left aligned. I wonder what I am doing wrong.
Thanks for any help!
+3
Susan mintz
source
to share
2 answers
If you put a constraint on your body, the div will only center within that.
Width / height should be set to div, not body.
body {
background-image: url('stjohnhusimages/green gradient.png');
background-repeat: no-repeat;
background-size: cover;
text-align:center;
}
Demo
+2
sachleen
source
to share
it is not required to have a fixed size of the width of the body, if the body has a fixed width, the inner div will not be centered and will depend on its size.
To center the div, the fixed width of the body should be removed
body {
background-image: url('stjohnhusimages/green gradient.png');
background-repeat: no-repeat;
background-size: cover;
text-align:center;
}
0
Alexander44
source
to share