So I can successfully center a div using the following CSS:
.container {
width: 1024px;
margin: 0 auto;
}
I then have the container inside the body tags, covering all the displayed page content. This works just fine.
The issue is that when I do the same thing but set the width to 100%, the page is no longer centered. This restricts how dynamic I can make my page, as I have to then create a container for each screen width (in px).
How can I create a container that will center my page with a width of 100%?
Many thanks.
if you want to just center a div within a container.Then you have style div within container as margin:0 auto; . Below is simple demonstration:
.container_
{
width:100%;
height:700px;
background:green;
}
.centreBox
{
width:50%;
height:50%;
margin:0 auto;
background:red;
}
<div class="container_">
<div class="centreBox">
</div>
</div>
And if you want div to place it horizontally as well as vertically in center
.container_
{
width:100%;
height:700px;
position:relative;
background:green;
}
.centreBox
{
width:50%;
height:50%;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
background:red;
}
<div class="container_">
<div class="centreBox">
</div>
</div>
And you want to place div with width 100% ,then it will occupy whole horizontal space available.There you can only apply vertical centering:
.container_
{
width:100%;
height:700px;
position:relative;
background:green;
}
.centreBox
{
width:100%;
height:50%;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
background:red;
}
<div class="container_">
<div class="centreBox">
</div>
</div>
Hope this helps :)