盒子水平垂直居中的需求在项目中可以说是非常常见,我所知的几种小妙招
1.定位利用子绝父相让盒子水平垂直居中:
<style>
.father {
position:relative;
width:600px;
height:600px;
background-color: pink ;
}
.son {
position:absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
width:200px;
height:200px;
background-color: orange;
}
</style>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
2.如果子元素宽高不确定,可以使用定位+位移的方式:
.father {
position:relative;
width:600px;
height:600px;
background-color: pink ;
}
.son {
position:absolute;
left: 50%;
top: 50%;
transform:translate(-50%, -50%)
width:200px;
height:200px;
background-color: orange;
}
3.可以利用margin:auto; 来实现
.father {
position:relative;
width:600px;
height:600px;
background-color: pink ;
}
.son{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: 200px;
height: 200px;
background-color: orange;
}
4.flex布局
.father {
display: flex;
justify-content: center;
align-items: center;
width:600px;
height:600px;
background-color: pink ;
}
.son{
width: 200px;
height: 200px;
background-color: orange;
}
5.利用display: table-cell
.father {
width:600px;
height:600px;
background-color: pink ;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.son{
width: 200px;
height: 200px;
background-color: orange;
display: inline-block;
}
你们还知道什么更好的方法吗?
欢迎大家评论留言,一起交流学习