<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>如何实现元素水平垂直居中</title>
<style>
h4{text-align:center;height:60px;margin:0 auto;width:700px;line-height:20px;}

.table{margin:0 auto;display:table-cell;vertical-align:middle;width:1910px; height:500px;text-align:center;border:#000 1px solid;
}
.relative{width:300px;height:300px;border:1px solid #000;margin:0 auto;}
.re-content{position:relative;left:50%;top:50%;margin-left:-50px;margin-top:-50px;}
.text{width:300px;height:300px;border:1px solid #000;margin:0 auto;line-height:300px;text-align:center;position:relative;}

.ab{position:relative;width:400px;height:400px;margin:0 auto;border:1px solid red;}
.ab div{left:0;top:0;right:0;bottom:0;margin:auto;position:absolute;}
.box{position:relative;width:400px;height:400px;margin:0 auto;border:1px solid red;display:-webkit-box;-webkit-box-pack:center; -webkit-box-align:center;}
</style>
</head>

<body>
<h4>使用表格显示法:把这个元素的容器设置为table-cell,也就是具有表格单元格的特性,再使用vertical-align(这个属性对block元素不起作用,但对table-cell元素是有效的)设置元素垂直居中,即可达到我们想要的效果。
  IE7及以下版本不支持此</h4>
<div class="table">
    <img style="width:100px;height:100px;border:1px solid red;"/>
</div>

<h4>综合利用相对定位及left,margin实现,IE6/7/8/9/10,FF,Chrome,Safari都支持</h4>
<div class="relative">
    <div class="re-content" style="width:100px;height:100px;border:1px solid red;"/></div>
</div>

<h4>综合利用相对定位及line-height,text-align实现行内元素,文字等垂直水平居中,IE6/7/8/9/10,FF,Chrome,Safari都支持</h4>
<div class="text">
    <span>文字居中</span>
</div>

<h4 >综合利用left,right,absolute,margin:auto定位,IE6/7不支持,其余都支持</h4>
<div class="ab">
    <div style="width:100px;height:100px;border:1px solid red;" ></div>
</div>

<h4 >综合利用弹性盒子模型进行定位</h4>
<div class="box">
    <div style="width:100px;height:100px;border:1px solid red;" ></div>
</div>
</body>
</html>

posted on 2016-07-09 01:50  alideali  阅读(203)  评论(0)    收藏  举报