首頁  >  文章  >  web前端  >  淺談使用CSS實現元素垂直居中的幾種方法

淺談使用CSS實現元素垂直居中的幾種方法

PHPz
PHPz轉載
2016-05-16 12:08:572692瀏覽

淺談使用CSS實現元素垂直居中的幾種方法

利用CSS進行元素的水平居中,行級元素設定其父元素的text-align center,區塊級元素設定本身的left和right margins為auto即可。本文收集了六種利用css進行元素的垂直居中的方法,一起看看吧!

Line-Height Method

line height demo
#試用:單行文字垂直居中,demo

程式碼:

html

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

css

##child {
    line-height: 200px;
}

垂直居中一張圖片,程式碼如下

html

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

css

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

CSS Table Method

table cell demo

#適用:通用,demo

##程式碼:

html

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

css##

#parent {display: table;}
#child {
    display: table-cell;
    vertical-align: middle;
}

低版本 IE fix bug:

#child {
    display: inline-block;
}

 Absolute Positioning and Negative Margin

absolute positioning and negative margin demo

#適用:區塊級元素,demo

#程式碼:

html

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

css

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

Absolute Positioning and Stretching

absolute positioning and vertical stretching demo

#適用:通用,但在IE版本低於7時無法正常工作,demo#

##程式碼:

html

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

css

##parent {position: relative;} #child {     position: absolute;     top: 0;     bottom: 0;     left: 0;     right: 0;     width: 50%;     height: 30%;     margin: auto; }
Equal Top and Bottom Padding

vertical centering with padding demo

#適用:通用,demo

程式碼:

##html

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

css

##

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

Floater p

適用:通用,demo

程式碼:

##html

    

    Content here


css

##parent {height: 250px;} #floater {     float: left;     height: 50%;     width: 100%;     margin-bottom: -50px; } #child {     clear: both;     height: 100px; }
以上就是六種方法,可以在實際的使用過程中合理選擇.

更多程式相關知識,請造訪:

程式設計入門! !

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除