CSS垂直居中的6種方法

一、單行文本垂直居中css

html:html

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

css:spa

.child{line-height: 200px}

    垂直居中一張圖片code

html:htm

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

css:圖片

.parent{line-height: 200px;border:1px solid #000;}
.parent img{vertical-align: middle}

二、css table 方法it

html:io

<div class="parent">
    <div class="child">text here</div>
</div>

css:table

.parent{display: table;border: 1px solid #000;height: 100px;}
.child{display: table-cell;vertical-align: middle}

 低版本的IE fix bug:class

.child{display:inline-block}

三、absolute positioning and negative margin,塊級元素

html:

<div class="parent">
    <div id="child"> 
        text here
    </div>
</div>

 css:

.parent{position:relative;border: 1px solid #000;height: 100px;width: 400px;}
.child{position: absolute;top:50px;left: 200px;height: 30px;width: 50px;
       border: 1px solid #000;margin: -15px 0 0 -25px;}

四、absolute positioning  and stretching,通用,>=IE7版本

html:

<div class="parent">
    <div id="child"> 
        text here
    </div>
</div>

css:

.parent{position:relative;border: 1px solid #000;height: 100px;width: 400px;}
.child{position: absolute;top:0;left: 0;right: 0;bottom:0;height: 30px;width: 50px;
       border: 1px solid #000;margin: auto;}

 五、equal top and bottom padding,通用

html:

<div class="parent">
    <div id="child"> 
        text here
    </div>
</div>

css:

.parent{padding: 5% 0;border: 1px solid #000;height: 100px;width: 400px;}
.child{padding: 10% 0;height: 30px;width: 50px;border: 1px solid #000;margin: 0 auto;}

六、float div 通用

html:

<div class="parent">
    <div class="floater"></div>
    <div class="child">text here</div>
</div>

css:

.parent{border: 1px solid #000;height: 250px;width: 400px;}
.floater{float: left;height:50%;width: 100%;margin-bottom: -50px;}
.child{clear:both;height: 100px;border:1px solid #000;}
相關文章
相關標籤/搜索