前端布局的時候總是會遇到一些需要居中的方案,下面是我平常使用的一些方法,當然還有很多的方法也能居中顯示。
1、寬高固定 – 使用絕對定位居中顯示
這兒一般是用在固定的大小的box中使用,如果相對定位的box大于螢幕不建議使用。
代碼如下:
<div class="box1">
<div></div>
</div>
<style type="text/css">
.box1{
position:relative;
height:500px;
width:500px;
background: #eee;
margin:0 auto;
}
.box1 div{
height:200px;
width:200px;
position:absolute;
left:50%;
top:50%;
margin:-100px 0 0 -100px;
background: #999;
</style>
2、寬高固定 – 使用固定定位居中顯示
固定定位主要是一些彈出層使用比較好,而且在所有的高度的文檔中都可以使用。
<div class="box2">
.box2{
position:fixed;
margin:-250px 0 0 -250px;
background: #eee;}
3、寬高不固定 – 螢幕中間 – 使用jq來計算
有些時候咱們會遇到高度和寬度不固定的box需要居中的需求,這時候咱們可以使用js來計算box的寬高然後在控制他的margin來居中。
<div class="box3"></div>
.box3{
width:600px;
height:600px;
padding:20px;}
<script type="text/javascript">
$('.box3').css({
'margin-top':-$('.box3').outerHeight(true)/2+'px',//擷取總高/2
'margin-left':-$('.box3').outerWidth(true)/2+'px' //擷取總寬/2
});
</script>
4、不固定寬高 – CSS上下左右居中 – IE7及以上
當然使用純CSS也是可以辦得到的,這個有個前提條件最外層的box必須有高度,然後可以使用display: table;來居中,如果你不想相容低版本浏覽器的話可以使用這個方法,當然這個方法親測可以支援到IE7。
<div class="box4">(www.gendan5.com)
<div>
<p>不固定寬高 - CSS上下左右居中 - IE7及以上</p>
.box4{
display: table;
border-collapse: collapse;
.box4>div{
display:table-cell;
vertical-align:middle;
text-align:center;
.box4>div>div{
background:#eee;
padding:20px;
line-height:28px;
display:inline-block;
5、上下左右定位法 – CSS上下左右居中 – IE7及以上