1.使用margin
进行固定长度的偏移
#father{
width: 100px;
height: 100px;
overflow:hidden;
background-color: aqua;
}
#son{
width: 50px;
height: 50px;
margin:0 auto;
margin-top:25px;//这里的距离应该是子盒子的一半
background-color: brown;
}
2.使用绝对定位并进行偏移
#father{
width: 100px;
height: 100px;
background-color: aqua;
position: relative;
}
#son{
width: 50px;
height: 50px;
background-color: brown;
position: absolute;
left: 50%;
margin-left: -25px;
top:50%;
margin-top: -25px;
/* 使用计算公式:
position: absolute;
left:calc(50%,-25px);
top:calc(50%,-25px); */
}
3.使用绝对定位并margin自适应进行居中
#father{
width: 100px;
height: 100px;
background-color: aqua;
position: relative;
}
#son{
width: 50px;
height: 50px;
background-color: brown;
position: absolute;
left: 0;
top:0;
right: 0;
bottom: 0;
margin: auto;
}
4.使用table-cell进行居中显示
#father{
width: 100px;
height: 100px;
background-color: aqua;
display: table-cell;
vertical-align: middle;
}
#son{
width: 50px;
height: 50px;
background-color: brown;
margin: 0 auto;
}
/*这段CSS代码的作用是将一个元素以表格单元格(table-cell)的形式呈现,并设置其
垂直对齐方式为居中(vertical-align: middle)。
`display: table-cell;` 的作用是将元素以表格单元格的形式呈现。表格单元格会自动
进行水平和垂直居中,类似于HTML表格中的单元格。使用这种布局方式可以方便地实现垂
直居中的效果。
`vertical-align: middle;` 的作用是设置元素的垂直对齐方式为居中。这会使元素相对
于其父容器的中心垂直居中,无论元素的高度是多少。
综合起来,这段代码的效果是将元素以表格单元格的形式呈现,并使其垂直方向上相对于
父容器居中对齐。这种技术常用于制作垂直居中的布局,特别适用于一些需要在未知高度的
容器中实现垂直居中的内容,比如垂直居中文本、图像等。*/
5.使用弹性盒子来实现居中
#father{
width: 100px;
height: 100px;
background-color: aqua;
display: flex;
justify-content: center;
align-items: center;
}
#son{
width: 50px;
height: 50px;
background-color: brown;
}