用css让一个容器水平垂直

本文转载自:@咸鱼老弟 http://www.cnblogs.com/xianyulaodi/p/5863305.html

这种css布局平时用的比较多,也是面试题常出的一个题,网上一搜一大丢,不过还是想自己总结一下。

这种方法比较多,本文只总结其中的几种,以便加深印象。

效果图都为这个:

方法一:position加margin

/**html**/
<div class="wrap">
<div class="center"></div>
</div>

/**css**/
.wrap {
width: 200px;
height: 200px;
background: yellow;
position: relative;
}
.wrap .center {
width: 100px;
height: 100px;
background: green;
margin: auto;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}

兼容性:主流浏览器均支持,IE6不支持

方法二: diaplay:table-cell

<!-- html -->
<div class="wrap">
<div class="center"></div>
</div>

/*css*/
.wrap{
width: 200px;
height: 200px;
background: yellow;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.center{
display: inline-block;
vertical-align: middle;
width: 100px;
height: 100px;
background: green;
}


兼容性:由于display:table-cell的原因,IE6\7不兼容

方法三:position加 transform

<!-- html -->
<div class="wrap">
<div class="center"></div>
</div>

/* css */
.wrap {
position: relative;
background: yellow;
width: 200px;
height: 200px;}

.center {
position: absolute;
background: green;
top:50%;
left:50%;
-webkit-transform:translate(-50%,-50%);
transform:translate(-50%,-50%);
width: 100px;
height: 100px;
}

兼容性:ie9以下不支持 transform,手机端表现的比较好。

本人比较推荐第三种,觉得比较好!

posted @ 2017-07-07 09:10  @circle  阅读(80)  评论(0)    收藏  举报