Centering Page Content Vertically
I know how I can horizontally center the entire page with CSS. But is there a way to vertically center the page? Something like this...
Solution 1:
You can also hijack CSS's display: table
and display: table-cell
for this purpose. The HTML would be like this:
<body><divid="body"><!-- Content goes here --></div></body>
And the CSS:
html,
body {
width: 100%;
height: 100%;
}
html {
display: table;
}
body {
display: table-cell;
vertical-align: middle;
}
If you want horizontal centering as well, then add this:
#body {
max-width: 1000px; /* Or whatever makes sense for you. */margin: 0 auto;
}
Some would call this an abuse of CSS but:
- It will work exactly the same pretty much everywhere.
- Requires minimal markup and styling.
- And CSS's vertical alignment deserves a bit of abuse; vertical alignment shouldn't require the hacking, contortions, and absolute sizing that it does.
References:
Solution 2:
There's a great article in MicroTut to do that http://tutorialzine.com/2010/03/centering-div-vertically-and-horizontally/
Centering with CSS:
.className{
width:300px;
height:200px;
position:absolute;
left:50%;
top:50%;
margin:-100px00 -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 a demo here
Post a Comment for "Centering Page Content Vertically"