xhtml元素水平居中方案总结

一个很不错的方案集合。提到了一些将元素水平居中的办法。其中最后一种很巧妙,很多人在用,不过我是第一次知道。文章于2007年56月10日 发布在http://www.12px.net

先来看我一个简单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都支持!

2005-08-12更新:此方法在IE下会导致不能使用鼠标选择某个区段的元素,注意注意!

相关文章