CSS网页布局DIV水平居中的各种方法
在Web标准中的页面布局是使用Div配合CSS来实现的。这其中最常用到的就是使整个页面水平居中的效果,这是在页面布局中基本,也是最应该首先掌握的知识。不过,还是经常会有人问到这个问题,在这里我简单总结一下使用Div和CSS实现页面水平居中的方法:%@2SE#j6X+a
一、margin:auto 0 与 text-aligh:center I @ o1@!z
在现代浏览器(如Internet Explorer 7、Firefox、Opera等)现代浏览器实现水平居中的方法很简单,只要设定到左右两侧的空白为自动即可。意即: t W [y6Y
:VS&D/y"E1~x
#wrap { margin:0 auto;} q\{Fo;G7Q
上面这段代码的意思是说使wrap这个div到左右两侧的距离自动设置,上下为0(可以为任意)。请在现代浏览器(如Internet Explorer 7、Firefox、Opera等)中运行现在的代码: G:gRvO
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"> BYu qi*bl ]
<head>
<title> new document </title> I4Xg1hgN%m
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
div#wrap { +`8t LZ r ]/Rzc
width:760px; q:_? nYt
margin:0 auto; ]T'dr;[b$VhL r5U.@3J
border:1px solid #333;
background-color:#ccc;
} 4u;r J9j9T|Q(qr
</style>
</head> ]@%Y8?u6l:m/i2T*D
<body> "e3]oU5_q;a
<div id="wrap"> q-@CY)e7]
在Firefox等现代浏览器设定页面元素的水平居中,只要指定margin:0 auto;即可
^pO_ O @['eS
<pre> ?}3]W%gM
div#wrap {
width:760px;
margin:0 auto; /*这里的0可以任意值*/
border:1px solid #ccc;
background-color:#999;
} D U;[5vdEn.BP2g~k
</pre> 9k7cY%Dy#^;Bd%q!U
</div> &t(w:Aay4z2am
</body> xAX@p
</html> 3K%zAz]-I:Z X
b%U4j&^4uF-B`#_ R#U
上面的效果很好。但是这在Internet Explorer 6及改正的版本中是不起作用的,不过幸好它有自己的解决办法。在Internet Explorer中text-align属性是可继承的,即在父元素中设置后在子元素中就默认具有了该属性。因此我们可以在body标签中设置text-align属性值为center,这样页面内所有的元素都会自动居中,同时我们还要加一个hook把页面中的文字变成我们习惯的阅读方式——居左对齐。因此我们要如此来写代码:
X%\5}*d Yy(sM
body {text-align:center;}
#wrap {text-align:left;} 4d+QwG[.l
_ AV!RY6v
这样在Internet Explorer中我们就轻松实现了Div的居中对齐。因此要在所有的浏览器中显示居中的效果,我们就可以这样写我们的代码:
body { text-align:center; } 9r1S|s1u!{1xT.f
#wrap { text-align:left;
margin:0 auto; :_,MV`7@
} g&v,Q"H+Ch9N#q
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> }`b9@J9q"v
<html xmlns="http://www.w3.org/1999/xhtml"> N(U4n)z^(S6rp*S1?4G
<head>
|(P|k.ZI ke
<title> CSS+Div实现水平居中对齐的页面布局 </title> p#p7LH/`_Lz#w$U|9n
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
body { text-align:center; } -PCsPK!I:X'D/x~ \
div#wrap { Y#Le1tX/^E9b0T0xx
text-align:left;
width:760px; Tuj1y#|+H
margin:0 auto;
border:1px solid #333; weD]N5E4~n
background-color:#ccc;
}
</style> 9^e8Y5X3y7c(A
</head>
<body> _wW:FV}~0N;W1H0S3x
<div id="wrap"> 2xi*M5ZKX2BCPb
~,x5Jr(d"p
在Firefox等现代浏览器设定页面元素的水平居中,只要指定margin:0 auto;即可
J }%P(Uwv:CE
<pre> /w4l b-gJ"Q5k B
div#wrap {
width:760px; wyU"P Kte5ICX!l1M
margin:0 auto; /*这里的0可以任意值*/ k rU,pU1FT$?l
border:1px solid #ccc; AOI5['\&X Z_#jw
background-color:#999; /b m#KU~
} 9D5wN2g1b&d6si0Z
y:Mq.E;J(w
在Internet Explorer 6 及以下的版本中我们还要做以下的设置:
body { text-align:center; } wd)IF4?TJe
div#wrap { Y,}}5bJ A%mF
text-align:left; 5j`/IyD2`or
} SV't)r;y2t6Oh] WT
</pre> r wOA+^,];H#Y.q
</div>
</body> 9A4t.? U8IS
</html> FX[A:G
a C,o&Z)bYr}
不过这里有一个前提,就是设置居中的元素要有固定的宽度,比如这里我们设定了为760像素。