寬度高度不固定的div 如何水平居中以及垂直居中

點評:從事頁面重構以來,由於經常遇見寬度不固定的div在水平或垂直居中的問題!總結下!留着以後用
寬度高度不固定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;} /*針對ie6 hack*/
.center a{float:left;border:1px solid #fff;padding:5px 10px;margin:10px;color:#fff;text-decoration:none;}

 

--------------------------------------------------------------------------------

代碼要點:
父容器container加css屬性 text-align:center;
子容器center加css屬性display:inline-block;
.center{_display:inline;} 爲針對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; }
#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%; }

 

--------------------------------------------------------------------------------

代碼要點:
父容器vc的css屬性 display:table;overflow:hidden;
子容器vci的css屬性 vertical-align:middle;display:table-cell;
針對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;}


--------------------------------------------------------------------------------

代碼要點
父容器要用相對定位position:relative;否則的話子元素會相對於瀏覽器窗口進行絕對定位。
子容器絕對定位,top:50%;left:50%;margin-top,margin-left的值取該容器高度,寬度的一半的負值。


--------------------------------------------------------------------------------

如果相對於瀏覽器窗口做水平垂直居中的話,比如需要大背景居中,代碼如下
<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>

詳細出處參考:http://www.jb51.net/css/56268.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章