在HTML中实现垂直水平居中的实用方法,适用于FF、IE6和IE7

6
什么是在HTML中垂直和水平居中内容的实用解决方案,适用于Firefox,IE6和IE7?
一些细节:
- 我正在寻找整个页面的解决方案。 - 您只需要指定要居中的元素的宽度。设计时不知道元素的高度。 - 当最小化窗口时,仅当所有空白都消失时才会出现滚动条。 换句话说,屏幕宽度应表示为:
"leftSpace width=(screenWidth-widthOfCenteredElement)/2"+ "centeredElement width=widthOfCenteredElement"+ "rightSpace width=(screenWidth-widthOfCenteredElement)/2"
并且对于高度也是同样:
"topSpace height=(screenHeight-heightOfCenteredElement)/2"+ "centeredElement height=heightOfCenteredElement"+ "bottomSpace height=(screenWidth-heightOfCenteredElement)/2"
- 实用意味着使用表格也可以。我打算将此布局主要用于特殊页面,如登录页面。因此,在这里CSS纯度并不重要,但遵循标准有助于未来的兼容性。
5个回答

4

来自http://www.webmonkey.com/codelibrary/Center_a_DIV

这是一个关于如何将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-->

2
<!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的解决方案也很不错。如果您知道需要居中对齐的内容的高度,似乎更好。

1

对于这个问题,您可以使用这种样式

#yourElement {
   margin:0 auto;
   min-width:500px;
}

1

对于水平方向:

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

你需要在body中使用text-align:left来修复IE渲染的一个bug。

0

这是您想要实现的吗?如果不是,请解释与下面图像有何不同?

alt text


通常来说,这不完全是我想要的。居中的内容应该是固定大小(以像素为单位),而不仅仅是屏幕的50%。 我通过仅指定内容的宽度来解决了这个问题。并且正在寻找不指定固定高度的解决方案。因此,此布局可用于具有不同但相同宽度的内容。 - Oleksandr Yanovets
当你调整窗口大小时,你的内容将始终保持相同的大小,但居中显示。 - Oleksandr Yanovets

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接