寬度高度不固定div的水平居中演示如下:
水平居中代碼:
html部分
<div class="container">
<div class="center"><a href="#">1</a><a href="#">2</a><a href="#">3</a>
<div style="clear:both"></div></div>
css部分
.container{width:500px;height:80px;background:#C2300B;margin-left:50px;padding-top:10px;text-align:center;}
.center{display:inline-block;border:2px solid #fff;}
.center{_display:inline;} /*針對(duì)ie6 hack*/
.center a{float:left;border:1px solid #fff;padding:5px 10px;margin:10px;color:#fff;text-decoration:none;}
代碼要點(diǎn):
父容器container加css屬性 text-align:center;
子容器center加css屬性display:inline-block;
.center{_display:inline;} 為針對(duì)ie6的hack
寬度高度不固定的div垂直居中演示如下:
我們垂直居中了,我們水平居中了
垂直居中代碼:
html部分
<div id="vc"><div id="vci"><div id="content">
我們垂直居中了,我們水平居中了
< /div></div></div>
css部分
#vc { display:table; background-color:#C2300B; width:500px; height:200px; overflow:hidden; margin-left:50px; _position:relative; }
#vci { vertical-align:middle; display:table-cell; text-align:center; _position:absolute; _top:50%; _left:50%; }
#content { color:#fff; border:1px solid #fff; display:inline-block; _position:relative; _top:-50%; _left:-50%; }
代碼要點(diǎn):
父容器vc的css屬性 display:table;overflow:hidden;
子容器vci的css屬性 vertical-align:middle;display:table-cell;
針對(duì)ie6的hack,vci容器的 _position:absolute;_top:50%; 和content容器的 _position:relative; _top:-50%;
如果不需要水平居中的話,需要注釋掉vci容器的text-align:center;_left:50%;以及content的display:inline-block;_left:-50%;
寬度高度固定的div垂直居中和水平居中
居中了
html部分
<div class="guding"><div class="gd">居中了</div></div>
css部分
.guding{width:500px;height:200px;background:#c2300b;margin-left:50px;position:relative;}
.gd{width:50px;height:20px;background:#fff;position:absolute;top:50%;left:50%;margin-top:-10px;margin-left:-25px;}
代碼要點(diǎn)
父容器要用相對(duì)定位position:relative;否則的話子元素會(huì)相對(duì)于瀏覽器窗口進(jìn)行絕對(duì)定位。
子容器絕對(duì)定位,top:50%;left:50%;margin-top,margin-left的值取該容器高度,寬度的一半的負(fù)值。
如果相對(duì)于瀏覽器窗口做水平垂直居中的話,比如需要大背景居中,代碼如下
<style type="text/css">
body{background:#c12b02;}
.main{background:url(你的背景圖片地址) no-repeat;width:1000px;height:800px;position:absolute;margin-top:-400px;margin-left:-500px;}
< /style>
< body>
< div class="main"></div>
< /body>