Center page content vertically

I know how I can center the entire page horizontally using CSS. But is there a way to vertically center the page? Something like that...


Example


+6
html css
source share
2 answers

MicroTut has a great article to do this http://tutorialzine.com/2010/03/centering-div-vertically-and-horizontally/

CSS Centering:

.className{ width:300px; height:200px; position:absolute; left:50%; top:50%; margin:-100px 0 0 -150px; } 

Centering with jQuery:

 $(window).resize(function(){ $('.className').css({ position:'absolute', left: ($(window).width() - $('.className').outerWidth())/2, top: ($(window).height() - $('.className').outerHeight())/2 }); }); // To initially run the function: $(window).resize(); 

And you can see the demo here

+9
source share

You can also grab CSS display: table and display: table-cell for this purpose. HTML will look like this:

 <body> <div id="body"> <!-- Content goes here --> </div> </body> 

And CSS:

 html, body { width: 100%; height: 100%; } html { display: table; } body { display: table-cell; vertical-align: middle; } 

If you also want horizontal centering, add the following:

 #body { max-width: 1000px; /* Or whatever makes sense for you. */ margin: 0 auto; } 

Some would call it CSS abuse, but:

  • It will work exactly the same almost everywhere.
  • Minimal markup and styling required.
  • And CSS vertical alignment deserves a bit of abuse; vertical alignment should not require hacking, distortion and the absolute size that it does.

Literature:

+6
source share

All Articles