div 垂直居中的六種方法

 利用CSS進行元素的水平居中,比較簡單,行級元素設置其父元素的text-align center,塊級元素設置其自己的left 和 right margins爲auto便可。本文收集了六種利用css進行元素的垂直居中的方法,每一種適用於不一樣的狀況,在實際的使用過程當中選擇某一種方法便可。css

1、spa

Line-Height Method

適用於設置行高 單行文本垂直居中,3d

<div id="parent">
<div id="child">Text here</div>
</div>

<style>
    #child {line-height: 200px;}
</style>

若是垂直一張圖片代碼以下:code

<div id="parent">
<img src="image.png" alt="" />
</div>

#parent {
line-height: 200px;
}
#parent img {
vertical-align: middle;
}

2、table-cell Method 通用

代碼以下:blog

<div id="parent">
<div id="child">Content here</div>
</div>

<style>
    #parent {display: table;}
    #child {
        display: table-cell;
        vertical-align: middle;
    }
</style>

<!--若是是IE8如下版本而要加如下css-->
<style>
    #child{display:inline-block;}
</style>


3、Absolute Positioning and Negative Margin 適用於塊級元素

代碼以下:圖片

<div id="parent">
<div id="child">Content here</div>
</div>

<style>
    #parent {position: relative;}
    #child {
        position: absolute;
        top: 50%;
        left: 50%;
        height: 30%;
        width: 50%;
        margin: -15% 0 0 -25%;
    }
</style>


4、Absolute Positioning and Stretching 通用,但在IE版本低於7時不能正常工做

代碼:it

<div id="parent">
<div id="child">Content here</div>
</div>

<style>
    #parent {position: relative;}
    #child {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 50%;
height: 30%;
margin: auto;
}
</style>


 

5、Equal Top and Bottom Padding 通用

代碼:
<div id="parent">
<div id="child">Content here</div>
</div>

<style>
    #parent {
padding: 5% 0;
}
#child {
padding: 10% 0;
}

</style>


6、Floater Div 通用

代碼:io

<div id="parent">
<div id="floater"></div>
<div id="child">Content here</div>
</div>

<style>
#parent {height: 250px;}
#floater {
float: left;
height: 50%;
width: 100%;
margin-bottom: -50px;
}
#child {
clear: both;
height: 100px;
}
</style>

相關文章
相關標籤/搜索