css实现水平垂直居中的几种方法

参考 http://www.w3cfuns.com/article-5598566-1-1.html

使用text-align和vertical-align和line-height来实现居中

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .cell{ margin:10px;background-color: #ccc; width:200px; height:200px; color:#457344; }
        .center1{text-align: center;  line-height: 200px;}
        .center1 span{vertical-align: middle;}
    </style>
</head>
<body>
<div class="cell center1">
    <img src="4.jpg"/>
</div>
<div class="cell center1">
     <span>ssssssssss</span>
</div>
</body>
</html>

这种方法使用text-align和vertical-align,line-height来实现居中,不过只适用于行内元素且不兼容IE6,第二种居中将解决IE6兼容问题。

position实现

position前面的’‘是用来兼容IE6

.center2{ text-align: center; _position: relative; 
line-height: 200px;}
.center2 span{ _position: absolute;  top:50%; left:50%;}
.center2 img{_position: relative; top:-50%;left:-50%;
 vertical-align: middle; }

table-cell

因为IE6,7不支持table-cell,所以IE6,7中显示不正常.设置元素的display:inline-block而具有行内元素的特性,因此可用text-align:center使其水平居中。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .center4{ 
            display: table-cell; //作为一个表格单元格显示
            vertical-align: middle; //垂直方向居中
            text-align: center //水平方向居中
        }
        .center4 div{
            width:100px; 
            padding:10px; 
            background:#333; 
            display: inline-block; //兼容IE6,使具有块级元素的特征,能使用text-align使其居中
        }   
    </style>
</head>
<body>
<div class="cell center4">
    <div>
      居中
    </div>
</div>
</body>
</html>

表格嵌套

既然IE6,7不支持table-cell,于是干脆使用表格嵌套使其居中,因为td已经默认设置了vertical-align:middle。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .center5 { text-align: center}
        .center5 div{ 
            display: inline-block; 
            width:100px;
            padding: 10px;
            background-color: #333;
        }
    </style>
</head>
<body>
<table >
    <tr>
      <td class="center5">
        <div>
         居中
         </div>
       </td>
       <td class="center5">
        <div>
            居中2
        </div>
       </td>
     </tr>
</table>
</body>
</html>

使用margin

使用

padding:0;
margin:auto;