1
<
body
>
2 < div id ="container" >
3 < h1 > content </ h1 >
4 < p > Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend. </ p >
5 </ div >
6 </ body >
2 < div id ="container" >
3 < h1 > content </ h1 >
4 < p > Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend. </ p >
5 </ div >
6 </ body >
使用自适应边界(auto margin)
水平居中任意元素的首选办法是使用边界(margin)性质(property),并把左右之值设置为auto。但你必须为#container指定一个宽度。
1
div#container
{
2 margin-left : auto ;
3 margin-right : auto ;
4 width : 168px ;
5 }
2 margin-left : auto ;
3 margin-right : auto ;
4 width : 168px ;
5 }
这个方案在任何当代浏览器上都有效,即使是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的值。
1
body
{
2 text-align : center ;
3 }
2 text-align : center ;
3 }
它公正地对待各种浏览器,十分彻底,唾手可得。然而,这是赋予文本的性质,它使#container中的文本也居中了。所以,在布局上我们还得做一些额外工作:
1
div#container
{
2 text-align : left ;
3 }
2 text-align : left ;
3 }
这样才可以把文本的对齐方式返回默认状状态。
综合边界和文本排列
因为文本排列向后兼容,当代浏览器也支持自适应边界,很多设计师把他们结合起来,实现跨浏览器使用。
1
body
{
2 text-align : center ;
3 }
4 #container {
5 margin-left : auto ;
6 margin-right : auto ;
7 border : 1px solid red ;
8 width : 168px ;
9 text-align : left
10 }
2 text-align : center ;
3 }
4 #container {
5 margin-left : auto ;
6 margin-right : auto ;
7 border : 1px solid red ;
8 width : 168px ;
9 text-align : left
10 }
唉,依然不完美,因为还是一个黑客技巧 (hack)。你不得不为文本排列写下多余的规则。但现在,我们可以使用更完美的跨浏览器的方案。
负边界解决方案
此方案得结合使用绝对定位(absolute positioning )。首先,把#container绝对定位并左偏移50%,这样,#container的左边界就是页面分辨率的一半。下一步,把#container的 左边界设置为负值,值大小为#container宽度(width)的一半。
1
#container
{
2 background : #ffc url(mid.jpg) repeat-y center ;
3 position : absolute ;
4 left : 50% ;
5 width : 760px ;
6 margin-left : -380px ;
7 }
2 background : #ffc url(mid.jpg) repeat-y center ;
3 position : absolute ;
4 left : 50% ;
5 width : 760px ;
6 margin-left : -380px ;
7 }
看,没有任何黑客技巧(no hacks)!连Netscape 4.x都支持!