For all your CSS lovers out there… there have been many times I have wanted to centre a div in the exact centre of the screen… the centre from head to toe and left to right. I have never managed to achieve this and speaking to fellow developers they have also struggled to find the answer to this. It was obviously possible as there are many website that have managed to achieve this affect and so it was only a matter of time till I really needed to do this and hunt down the answer… and today was that day.
It’s actually quite simple if you put your mind to it. Using absolute positioning you can position an element by taking it out of the document flow. Other elements in the normal flow of the document will act as though the absolute positioned element was never there.
width:970px;
height:710px;
position: absolute;
top:50%;
left: 50%;
By setting the left position to 50% it will set the div to start in the centre of the screen. By adjusting the left margin by a value half of the size of the div we are centring, we can move the entire div to the left and place it directly in the centre of the page.
width:970px;
height:710px;
position: absolute;
top:50%;
margin-top:-355px;
left: 50%;
margin-left:-485px;
and that’s it done… until the next time…
The problem with that is that you cannot set is to be centre of the screen top-bottom only left-right. Also using this method allows you to position:absolute; the container thus allowing you to use absolute positining inside… which I needed to do at the time.To just centre a div you can use something like:div.container {width:860px;margin-left:auto;margin-right:auto;}
That is a long way to do it!use this method instead..container {text-align:center;}.centerdiv {margin:0 auto;width: 800px;}It is very important that you specify the width.