在FF,IE6和IE7中运行的HTML中垂直和水平居中的实用解决方案

时间:2020-03-05 18:49:14  来源:igfitidea点击:

在Firefox,IE6和IE7中可以正常使用的HTML内容在垂直和水平居中的解决方案是什么?

一些细节:

  • 我正在寻找整个页面的解决方案。
  • 我们只需要指定要居中的元素的宽度。元素的高度在设计时未知。
  • 最小化窗口时,仅当所有空白都消失时才应出现滚动。换句话说,屏幕的宽度应表示为:

" leftSpace width =(screenWidth-widthOfCenteredElement)/ 2" +
" centeredElement width = widthOfCenteredElement" +
" rightSpace宽度=(screenWidth-widthOfCenteredElement)/ 2"

和高度相同:

" topSpace高度=(screenHeight-heightOfCenteredElement)/ 2" +
" centeredElement height = heightOfCenteredElement" +
" bottomSpace高度=(screenWidth-heightOfCenteredElement)/ 2"

  • 实际上,我的意思是表的使用是可以的。我打算将这种布局主要用于登录之类的特殊页面。因此,CSS纯度在这里并不是那么重要,而为了将来的兼容性,需要遵循以下标准。

解决方案

回答

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title>Centering</title>
 <style type="text/css" media="screen">
  body, html {height: 100%; padding: 0px; margin: 0px;}
  #outer {width: 100%; height: 100%; overflow: visible; padding: 0px; margin: 0px;}
  #middle {vertical-align: middle}
  #centered {width: 280px; margin-left: auto; margin-right: auto; text-align:center;}
 </style> 
</head>
<body>
 <table id="outer" cellpadding="0" cellspacing="0">
  <tr><td id="middle">
   <div id="centered" style="border: 1px solid green;">
    Centered content
   </div>
  </td></tr>
 </table>
</body>
</html>

来自community.contractwebdevelopment.com的解决方案也是一个很好的解决方案。而且,如果我们知道需要居中放置的内容的高度似乎会更好。

回答

对于水平:

<style>
body
{
    text-align:left;
}
.MainBlockElement
{
    text-align:center;
    margin: 0 auto;
}
</style>

我们需要在正文中使用text-align:left来修复IE渲染中的错误。

回答

这是我们要完成的工作吗?如果不是,请说明与下图有何不同?

回答

从http://www.webmonkey.com/codelibrary/Center_a_DIV

#horizon        
    {
    text-align: center;
    position: absolute;
    top: 50%;
    left: 0px;
    width: 100%;
    height: 1px;
    overflow: visible;
    display: block
    }

#content    
    {
    width: 250px;
    height: 70px;
    margin-left: -125px;
    position: absolute;
    top: -35px;
    left: 50%;
    visibility: visible
    }

<div id="horizon">
   <div id="content">
      <p>This text is<br><emphasis>DEAD CENTRE</emphasis ><br>and stays there!</p>
   </div><!-- closes content-->
</div><!-- closes horizon-->