我们在日常工作中,常常会需要让一个子盒子,在父盒子里面水平居中和垂直居中,那么实现这个效果,有哪常见的方法呢?
1.定位+margin
<style>
.father{
position: relative;
width: 600px;
height: 600px;
background-color: aqua;
margin: 0 auto;
}
.son{
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
width: 200px;
height: 200px;
background-color: red;
}
</style>
2.定位+位移
<style>
.father{
position: relative;
width: 600px;
height: 600px;
background-color: aqua;
margin: 0 auto;
}
.son{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
width: 200px;
height: 200px;
background-color: red;
}
</style>
3.定位+margin
<style>
.father{
position: relative;
width: 600px;
height: 600px;
background-color: aqua;
margin: 0 auto;
}
.son{
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto auto;
width: 200px;
height: 200px;
background-color: red;
}
</style>