垂直水平居中的四种方法

方法一 待居中元素具有确定的高度和宽度

css:

.parent{

positive:relative;

}

.child{

width:200px;

height:200px;

positive:absolute;

left:50%;

top:50%;

margin-left:-100px;     <!--1/2宽度-->

margin-top:-100px;   <!--1/2高度-->

}

方法二: 待居中元素具有确定的高度和宽度

css:

.parent{

width:500px;

height:500px;

positive:relative;

}

.child{

positive:absolute;

left:50%;

top:50%;

transform:translate(-50%,-50%)

}

方法三: 使用flexbox

css:

.parent{

width:500px;

height:500px;

display:flex;

justify-content:center;

align-items:center;

}

方法四、使用table,增加一层嵌套

css:

.task{
display: table;
width: 500px;
height: 500px;
border: 1px solid #999;
}
.box-wrap{
display: table-cell;
vertical-align: middle;       <!--垂直居中-->
}
.box-set{
margin: 0 auto;                <!--水平居中-->

width:200px;

height:200px;

background-color: gray;
}

html:
<div class="task">
<div class="box-wrap">    <!--增加的一层嵌套-->
<div class="box-set">
</div>
</div>
</div>

posted @ 2016-03-16 17:20  bottle_小姐  Views(329)  Comments(0)    收藏  举报