将网站对齐到浏览器的垂直中间位置

时间:2012-02-02 12:34:04

标签: javascript html css

我有一个高度为490像素的网站。我需要将整个网站放在浏览器的垂直中间位置。

任何建议!!!

5 个答案:

答案 0 :(得分:0)

<body style="text-align: center">
    <div style="text-align: left; width: 950px">content</div>
</body>

答案 1 :(得分:0)

<html>
  <head>
    <title>vertical align</title>
    <style>
      * {margin:0px;padding:0px}
      #content {height:490px; width:960px; position:absolute; border: 2px #000 solid}
    </style>
    <script>
      function resize(){
        var content = document.getElementById('content');
        var body = document.getElementsByTagName('body')[0];
        if(window.getComputedStyle){
          var bodyHeight = window.getComputedStyle(body).height.replace('px','');
        }else if(body.runtimeStyle){
          var bodyHeight = body.offsetHeight;
        }
        content.style.top = (bodyHeight - 490)/2 + 'px';
      }
      window.onresize = window.onload = resize;
    </script>
  </head>
  <body>
    <div id="content">
    </div>
  </body>
</html>

答案 2 :(得分:0)

#content{ 
    height: 490px; 
    margin-top: -245px; 
    top: 50% 
}

答案 3 :(得分:0)

传统的方法是使用表并设置vertical-align:middle;,但使用表格进行布局现在被认为是不好的做法。新的解决方案是灵活的盒子布局,但仍然没有得到广泛的支持。所以,这是一个中间解决方案。这有点hackish,但它在每个浏览器中完成工作,不使用表。 (live demo

<!doctype html>
<html lang='en'>
  <head>
    <meta charset='utf-8'>
    <title>positioning test</title>
    <style type='text/css'>
      *        {margin:0; padding:0;}
      body     {position:absolute; width:100%; height:100%;}
      #pad     {height:50%; min-height:245px;}
      #content {height:490px; margin-top:-245px;
                background:#f88; border:2px solid #000;}
    </style>
  </head>
  <body>
    <div id='pad'></div>
    <div id='content'></div>
  </body>
</html>

请不要使用javascript - 除非绝对必要,否则使用javascript作为布局是一个非常糟糕的主意,为此它肯定没有必要。另请注意,您无法合并两个div,只需设置#content {position:absolute; top:50%;},因为#pad必须具有正确的min-height,否则某些内容将隐藏在短于490px的窗口中(494px,例子)。

答案 4 :(得分:0)

链接到垂直对齐页面就在这里.... Here

只是查看页面来源&amp;你会知道怎么做