日期:2013-10-24  浏览次数:20735 次

先来看我一个简单XHTML/HTML文件代码(部分),我们的目的是让#container水平居中。

<body>
  <div id="container">
    <h1>content</h1>
    <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
  </div>
</body>

使用自顺应边界(auto margin)

水平居中任意元素的首选办法是使用边界(margin)性质(property),并把左右之值设置为auto。但你必须为#container指定一个宽度。

div#container {
margin-left: auto;
margin-right: auto;
width: 168px;
}

这个方案在任何当代浏览器上都无效,即便是IE6,前提是在web标准兼容模式下(compliance mode)。不幸的是,它不会在先前版本的IE/Win中任务。我们为此列一个表格:
浏览的自顺应边界支持一览表 浏览器   版本   支持
Internet Explorer   6.0, compliance mode   是
Internet Explorer   6.0, quirks mode   否
Internet Explorer   5.5 Windows   否
Internet Explorer   5.0 Windows   否
Internet Explorer   5.2 Macintosh   是
Mozilla   所有当前版本   是
Mozilla Firefox   所有版本   是
Netscape   4.x   否
Netscape   6.x+   是
Opera   6.0, 7.0 Macintosh and Windows   是
Safari   1.2   是

虽然遭到浏览器支持的限制,大部分设计师还是提倡你尽可能这样做。但我们仍然可以使用CSS应付一切情况。


使用文本陈列(text-align)

此方案需求使用到text-align性质,使用给body元素并且赋予center的值。

body {
text-align: center;
}

它公正地对待各种浏览器,十分彻底,唾手可得。然而,这是赋予文本的性质,它使#container中的文本也居中了。所以,在规划上我们还得做一些额外任务:

div#container {
text-align: left;
}

这样才可以把文本的对齐方式前往默认状形状。

综合边界和文本陈列

由于文本陈列向后兼容,当代浏览器也支持自顺应边界,很多设计师把他们结合起来,实现跨浏览器使用。

body {
text-align: center;
}
#container {
margin-left: auto;
margin-right: auto;
border: 1px solid red;
width: 168px;
text-align: left
}

唉,仍然不完满,由于还是一个黑客技巧 (hack)。你不得不为文本陈列写下多余的规则。但如今,我们可以使用更完满的跨浏览器的方案。

负边界处理方案

此方案得结合使用绝对定位(absolute positioning )。首先,把#container绝对定位并左偏移50%,这样,#container的左边界就是页面分辨率的一半。下一步,把#container的左边界设置为负值,值大小为#container宽度(width)的一半。

#container {
background: #ffc url(mid.jpg) repeat-y center;
position: absolute;
left: 50%;
width: 760px;
margin-left: -380px;
}

看,没有任何黑客技巧(no hacks)!连Netscape 4.x都支持!