CSS基础之实现子盒子在父盒子中水平垂直居中
总结用css实现水平垂直居中的常用方法
1.使用flex布局:
<style type="text/css">
.Father {
width: 200px;
height: 200px;
border: 1px solid #000;
display: flex;
justify-content: center;
align-items: center;
}
.Son {
width: 100px;
height: 100px;
background-color: black;
}
</style>
2.使用"子绝父相"
.Father {
width: 200px;
height: 200px;
position: relative;
border: 1px solid #000;
}
.Son {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
3.也是使用子绝父相
.Father {
width: 200px;
height: 200px;
position: relative;
border: 1px solid #000;
}
.Son {
width: 100px;
height: 100px;
background-color: blue;
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
margin: auto;
}
4.使用网格布局
<style type="text/css">
.Father {
width: 200px;
height: 200px;
display: grid;
border: 1px solid #000;
}
.Son {
width: 100px;
height: 100px;
justify-self: center;
align-self: center;
background-color: pink;
}
</style>
5.使用table-cell(注意要把需要居中的盒子设置为display:inline-block)
<style type="text/css">
.Father {
width: 200px;
height: 200px;
display: table-cell;
text-align: center;
vertical-align: middle;
border: 1px solid #000;
}
.Son {
display: inline-block;
width: 100px;
height: 100px;
background-color: aqua;
}
</style>
以上是本人知道的部分关于子盒子在父盒子中水平垂直居中的做法,可能有些做法不好,希望可以指正,我是小白,谢谢指教 !