2009-08-28 40 views
0

我无法让我的网站以CSS为中心。我已经尝试了所有的网络,包括各地提出的常用方法:无法获得CSS元素居中

body { 
    text-align: center; 
} 
#container { 
    width: 770px; 
    margin: 0 auto; 
    text-align: left; 
} 

然后使用

<div id="container> 
<!-- Centered Content Goes here--> 
</div> 

,但它只是不会去市中心。它停留在页面的左侧。

的CSS的,我想为中心元素的一个例子是这样的:

#topHeader 
{ 
    background:url(images/top_header.jpg); 
    position:absolute; 
    width: 695px; 
    height: 242px; 
    top: 0px; 
    left: 0px; 
} 

所以,我的HTML应该是这样的:

<div id="container> 
<div id="topHeader></div> 
<!-- All other elements go here as well--> 
</div> 

但正如我之前提到的,该元素保持放置。 谢谢! 埃里克

回答

0

主要问题是您的#topHeader元素的绝对定位。因为您已将它完全放在top: 0px; left: 0px;的位置,这正是它将要定位的位置 - 位于页面的左上角。

#topHeader元素中删除绝对位置开始。

-2

据我所知,它根本不起作用。 text-align以文本或内联内容为中心,而不是块元素。

编辑:另一方面,粉碎机的链接是有道理的。不幸的是,只有固定大小的块。

+0

深红色,你不能在不知道其宽度的情况下居中块元素。 –

0

您将标题绝对放置,因此它与包含的块(即body)偏移,而不是父元素。你想要的是相对定位。

绝对

的框的位置(以及可能的尺寸)与 '顶部', '右', '底部',和 '左' 属性指定。这些属性指定 相对于框的 包含块的偏移量。绝对的 定位框取出 正常流程。这意味着他们没有 影响后面的 兄弟姐妹的布局。此外,虽然绝对定位盒子有边距,但他们做的 不会与任何其他边距合拢。

- 9.3.1 Choosing a positioning scheme: 'position' property

绝对:

<html> 
    <head> 
     <style type="text/css"> 
      body { 
       text-align: center; 
      } 
      #container { 
       color:blue; 
       border:1px solid blue; 

       width: 770px; 
       margin: 0 auto; 
       text-align: left; 
      } 
      #topHeader 
      { 
       color:red; 
       border:1px solid red; 

       position:absolute; 
       width: 695px; 
       height: 242px; 
       top: 0px; 
       left: 0px; 
      }  
     </style> 
    </head> 
    <body> 
     outside 
     <div id="container"> 
      inside 
      <div id="topHeader">deep inside</div> 
      <!-- All other elements go here as well--> 
     </div> 
    </body> 
</html> 

相对:

<html> 
    <head> 
     <style type="text/css"> 
      body { 
       text-align: center; 
      } 
      #container { 
       color:blue; 
       border:1px solid blue; 

       width: 770px; 
       margin: 0 auto; 
       text-align: left; 
      } 
      #topHeader 
      { 
       color:red; 
       border:1px solid red; 

       position:relative; 
       width: 695px; 
       height: 242px; 
       top: 0px; 
       left: 0px; 
      }  
     </style> 
    </head> 
    <body> 
     outside 
     <div id="container"> 
      inside 
      <div id="topHeader">deep inside</div> 
      <!-- All other elements go here as well--> 
     </div> 
    </body> 
</html> 
5

与此 dead centre

+0

+1,我喜欢这个主意。 –

+0

令人敬畏的例子。将它添加到我的CSS技术作弊列表中。 –

+0

+1好资源。 –

0

尝试增加这哟顶端试你的css文件:

// Wipes out any preexisting padding and margin. 
html, body { 
    padding: 0; 
    margin: 0; 
} 

然后添加一个位置:relative;指导你想要中心的课程。实际上,可以尝试将它添加到HTML中,以便所有类都使用相对位置。这可能是你有位置:绝对;设置,然后结合左:0px;强制你的头部包含忽略边距:0 auto;并留在页面的左侧。

0

尝试所有这些居中方法时要检查的一件事是确保您的文档类型对于正在使用的方法是正确的。

希望这对你有帮助。