[英]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?
如果CSS不够强大,我可以使用Javascript完成此工作吗? 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 1)如果您的内容确实是一个已知的固定高度,则可以使用
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: 2)如果您不在乎它在IE7及更低版本中的工作方式是否相同,请按如下所示设置CSS:
html { display: table; }
body { display: table-cell; vertical-align: middle; }
If you don't mind adding non-semantic markup, you can do this: 如果您不介意添加非语义标记,则可以执行以下操作:
html: HTML:
<div class="pusher"></div>
<div class="center"></div>
CSS: 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/ 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. 如果您确实关心语义标记,并且必须支持较旧的浏览器,那么您将不得不使用JavaScript。 Here's one solution using jQuery :
这是使用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/ 这是小提琴: http : //jsfiddle.net/dw3rc/
I've often done this with setting height:50% and padding-top:25% but that's not always suitable. 我经常通过设置height:50%和padding-top:25%来做到这一点,但这并不总是合适的。
This page identifies a different technique that might work: 此页面标识了可能有效的另一种技术:
http://www.jakpsatweb.cz/css/css-vertical-center-solution.html http://www.jakpsatweb.cz/css/css-vertical-center-solution.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.