APP

如何实现div水平垂直居中

四种方法可实现div水平垂直居中

一、flex 布局

<style>        
.box{
width: 300px;
height: 300px;
background-color: #ccc;
display: flex;
display: -webkit-flex;
justify-content: center;
align-items: center;
}
.box .a{
width: 100px;
height: 100px;
background-color: blue;
}
</style>
HTML 代码:
<div class="box">
<div class="a"></div>
</div>


二、position 

 父元素设置为:position: relative; 

 子元素设置为:position: absolute; 距上50%,据左50%,然后减去元素自身宽度的一半距离就可以实现

<style>        
.box{
width: 300px;
height: 300px;
background-color: red;
position: relative;
}
.box .a{
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
left: 50%;
top: 50%;
margin: -50px 0 0 -50px;
}
</style>

HTML 代码:
<div class="box">
<div class="a">love</div>
</div>


三、position transform

如果元素未知宽度,只需将上面例子中的 margin: -50px 0 0 -50px;替换为:transform: translate(-50%,-50%);

<style>        
.box{
width: 300px;
height: 300px;
background-color: red;
position: relative;
}
.box .a{
background-color: blue;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>


四、position(元素已知宽度)(left,right,top,bottom为0,maigin:auto )

<style>        
.box{
width: 300px;
height: 300px;
background-color: red;
position: relative;
}
.box .a{
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
</style>
HTML 代码:
<div class="box">
<div class="a">love</div>
</div>



已邀请:

要回复问题请先登录注册