如何垂直对齐HTML文档的正文标记? [英] How do you vertically align the body tag of an HTML document?

查看:91
本文介绍了如何垂直对齐HTML文档的正文标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个水平居中但相当短的网页,它只占据垂直页面的一半。我想要它的中心。如何垂直居中标记?我不能有一个静态高度,所以这不是一个选项。如果CSS不够强大,我可以使用Javascript来完成这个吗?非常感谢!

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!

推荐答案

如果您不介意添加非语义标记,可以这样做:

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/

如果你在乎关于语义标记,并且必须支持旧的浏览器,那么你必须诉诸JavaScript为此。以下是使用 jQuery 的一种解决方案:

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();

这里是小提琴: http://jsfiddle.net/dw3rc/

这篇关于如何垂直对齐HTML文档的正文标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆