简体   繁体   中英

How do you vertically align the body tag of an HTML document?

I have a webpage that is horizontally centered but is rather short - it only takes up half the vertical page. I want it to be centered. How can I center the tag vertically? I cannot have a static height, so that is not an option. if CSS is not powerful enough, can I use Javascript to accomplish this? Thanks!

Two primary ways, neither of which is especially perfect, but widely used:

1) if your content really is a fixed, known height, then you CSS position it with

position: absolute;
top: 50%;
margin-top: here, set a pixel value that's equal to: -1 * (content height / 2)

2) If you don't care if it works the same way in IE7 and below, set CSS as follows:

html { display: table; }
body { display: table-cell; vertical-align: middle; }

If you don't mind adding non-semantic markup, you can do this:

html:

<div class="pusher"></div>
<div class="center"></div>

CSS:

html, body {
    height: 100%;
}
.pusher {
    height: 100%;
    margin-bottom: -50%;
}
.center {
    background: green;
    width: 400px;
    height: 200px;
    margin: 0 auto;
}

http://jsfiddle.net/Jsqqk/


If you do care about semantic markup, and have to support older browsers, then you'll have to resort to JavaScript for this. Here's one solution using jQuery :

var $window = $(window),
    $container = $('#container');

$window.resize(function(){
    $container.css('margin-top',
        Math.max(($window.height() / 2) - ($container.height() / 2), 0)
    );
}).resize();

And here's the fiddle: http://jsfiddle.net/dw3rc/

I've often done this with setting height:50% and padding-top:25% but that's not always suitable.

This page identifies a different technique that might work:

http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM