盒子水平垂直居中的方法
结构代码
<div class="father" id="father">
<div class="son" id="son"></div>
</div>
1、position+margin实现(需要定义自身的width和height)
<style type="text/css">
.father{
position: relative;
width: 400px;
height:400px;
background: blue;
}
.son{
position:absolute;
left: 50%;
top:50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
background : pink;
}
</style>
2、position+transifrom(不同定义自身的width和height,自动算出元素width的一半和height的一半)
.father{
position: relative;
width: 400px;
height: 400px;
background: blue;
}
.son{
position: absolute;
left: 50%;
top:50%;
transform: translate( -53%, -50%);
background: pink;
}
3、第三种方法(需要定义自身的width和height,但不用管width和height多少)
.father{
position: relative;
width: 400px;
height: 400px;
background: blue;
}
.son{
position: absolute;
top:0;
bottom:0;
left:0;
right:0;
height: 100px;
width: 100px;
margin: auto;
background: pink;
}
4、通过flex弹性布局实现(不用定义自身的width和height)
.father{
display: flex;
justify-content : center;
align-items: center;
width: 400px;
height: 400px;
background: blue;
}
.son{
background: pink;
}
5、通过js实现
<script type="text/javascript">
window.onload=function(){
var fatherWidth=father.offsetWidth;
var fatherHeight=father.offsetHeight;
var sonWidth=son.offsetWidth;
var sonHeight=son.offsetHeight;
son.style.position="absolute";
son.style.left=(fatherWidth-sonWidth)/2+"px";
son.style.top=(fatherHeight-sonHeight)/2+"px";
}
</script>
6、第六种实现水平垂值居中的方法
<style type="text/css">
.father{
//父元素必须要定义宽度和高度且不能为百分比,子元素要设置为行内快元素
display: table-cell;
text-align: center;
vertical-align: middle;
width: 400px;
height: 400px;
background: blue;
}
.son{
display: inline-block;
width: 100px;
height: 100px;
background: pink;
}
</style>
效果