Centre a div using absolute positioning
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…
2 Comments
Leave a comment
Recent Posts
Categories
- Blog (43)
- Code (1)
- Codeigniter (2)
- FuelPHP (1)
- Refresh Teesside (1)
What I'm Doing...
- @stublackett awesome snowman my man! 13 hrs ago
- @xocs a computer ban! love it! No worries. 14 hrs ago
- @xocs if I email you some links can you add them to the @refreshteesside website? 17 hrs ago
- More updates...
Tags
Archives
- January 2012 (1)
- October 2011 (2)
- August 2011 (1)
- March 2011 (2)
- February 2011 (1)
- August 2010 (1)
- May 2010 (1)
- April 2010 (1)
- March 2010 (2)
- January 2010 (1)
- November 2009 (1)
- October 2009 (1)
- September 2009 (1)
- August 2009 (3)
- July 2009 (3)
- June 2009 (1)
- April 2009 (1)
- March 2009 (2)
- February 2009 (2)
- December 2008 (1)
- November 2008 (1)
- October 2008 (2)
- September 2008 (1)
- August 2008 (1)
- July 2008 (3)
- June 2008 (2)
- May 2008 (7)







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.
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;
}