I have multiple nested div's
that follow the flow of the document that contain some content and footer information. Each div
has an id
and the one named content
is constrained using the width
css
property to about 800px
.
The problem I have is that when I expand the webpage, the div
content
with all its nested div's
remains at the top left corner of the webpage with the 30px
margin
. I want the content
div
and all its nested div's
to be in the centre of the div
main
. I thought I could achieve this by applying the css
style margin 0 auto;
. I have attached an image to try and illustrate what I mean. The first image demonstrates the behaviour of my website as it stands.
EDIT:
Here is my code. I can provide more if needed:
<!doctype html>
<html>
<head>
<style type="text/css">
body {
margin: 30px;
}
#main {
margin: 0 auto;
}
</style>
</head>
<body>
<div id="main">
<div id="main_index">
<div id="content"></div>
<div id="footer"></div>
</div>
</div>
</body>
</html>
This solution will only work if the #content
is smaller than the #main
, which is basically the screen size.
First make sure that #main
takes up 100% of the height of the screen by giving the html
, body
and #main
a height: 100%
.
To position the #content
in the horizontal and vertical center of the #main
it will be positioned absolutely. To let it have #main
as it's frame of reference add position: relative
to the #main
. The #content
gets a top: 50%
and left: 50%
which makes the top left of the #content
start at exactly the center of the #main
. The #content
gets a transform: translate(-50%, -50%)
to nudge it 50% of its width to the left and 50% of its height to the top. This makes it perfectly centered.
html, body { height: 100%; } #main { position: relative; height: 100%; } #content { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .box { border: 1px solid #c66; background-color: #f99; width: 300px; height: 300px; }
<div id="main"> <div id="content""> <div class="box"></div> </div> </div>
the margin: 0 auto;
wont work unless u give the div a width because if u think about it ,how the browser will calculate the distance from both sides if the div doesn't have a width ?,
u can also align a div in middle with text-align: center;
, but for the vertical centering there a couple of ways
position: absolute;
trick or use the vertical-align: middle
but this needs a display: inline-block;
or it wont work.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.