
Let’s say that you have a website or a div that you need to place in the center of of the page both horizontally and vertically. You may be creating a pop-up window or a centered website, as long as your site has a set height and width it’s easy to center it.
As an example let’s assume that your website is 800px wide and 400px high. Here is the HTML along with the CSS to center this website exactly in the middle of the page horizontally and vertically.
The HTML:
<div class="center"> Your website goes here. </div>
The CSS:
.center { width: 800px; height: 400px; position: absolute; left: 50%; top: 50%; margin-left: -400px; margin-top: -200px; }
Basically you just need to make sure that the left margin is half of your website width and that the top margin is half of the website height. If you only want to center your website horizontally then simply remove the “top:50%” and “margin-top:-200px” from the CSS.
(Awesome meditation image by Emils Blums).
Nice Adham!!!!
No one knows its damn easy =)
thank you very much man, I did used in flash intro page,
amazing…
Thanks alot…
This is a great tip, thanks!! by the way, this website is SO cool! I love the design!
very simple and nice trick. thanks for sharing
Excellent and insightful post! It’s short and to the point, and can easily be implemented for any site. 🙂
how do you keep from cutting off the top and sides when the screen is smaller than your site?
@ivyaj – I would probably use “margin:auto” instead of absolute positioning. Alternatively you could use some JS to detect the size of the window and adjust your positioning accordingly. 🙂
Nice and simple 🙂 Thanks for sharing!
Why not use “margin:auto;”?
@Raven – Why not indeed. This is just another way of doing it in case you can’t use margin:auto; 🙂
@Raven – yes you can use “margin:auto” but that will only center the website/element horizontally and not “vertically”.
@adham – Thanks for sharing such a simple & neat approach. 🙂
You can use margin:0 auto if you indicate the width property in div.