realazy


元素水平居中方案总结

先来看我一个简单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下会导致不能使用鼠标选择某个区段的元素,注意注意!

抄袭文献:The Zen of CSS Design

One Response to “元素水平居中方案总结”

  1. realazy » 垂直对齐的两个方案 Says:

    [...] 下面这种方案使用相对定位和绝对定位相结合的办法。这种办法底对齐十分有效,但需要垂直居中或者水平居中,则需要强制定义该元素的宽度和高度。在此只举例底对齐,需要垂直/水平居中对齐留待大家研究,可以参考我以前的水平居中的文章:元素水平居中方案总结的“负边界解决方案”一节。 [...]

Leave a Reply


realazy (懒到死) is proudly powered by WordPress | Entries (RSS) and Comments (RSS)