通过定位,给父盒子相对定位,给子盒子绝对定位,top.left为50%,再margin-top:-(子盒子高的一半)px,margin-left:-(子盒子宽的一半)px
注:需要知道盒子的宽高
<style>
div {
position: relative;
height: 400px;
width: 400px;
background-color: pink;
}
span {
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px;
margin-top: -50px;
display: block;
width: 100px;
height: 100px;
background-color: purple;
}
</style>
不依赖计算盒子宽高进行定位,可以用transform:translate 移动自身的一半就行
<style>
div {
position: relative;
height: 400px;
width: 400px;
background-color: pink;
}
span {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: block;
width: 100px;
height: 100px;
background-color: purple;
}
</style>
子盒子定位时,top.left.bottom.right都设置为0,然后设置margin:auto , 也能实现居中
<style>
div {
position: relative;
height: 400px;
width: 400px;
background-color: pink;
}
span {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
display: block;
width: 100px;
height: 100px;
background-color: purple;
}
</style>
通过flex布局,设置垂直和水平都居中( 设置为水平居中justify-content: center; 设置为垂直居中align-items: center;)
<style>
div {
display: flex;
justify-content: center;
align-items: center;
height: 400px;
width: 400px;
background-color: pink;
}
span {
display: block;
width: 100px;
height: 100px;
background-color: purple;
}
</style>
通过flex布局,给子盒子设置margin:auto
<style>
div {
display: flex;
height: 400px;
width: 400px;
background-color: pink;
}
span {
margin: auto;
width: 100px;
height: 100px;
background-color: purple;
}
</style>
通过display:table-cell 给子盒子设置display:inline-block,父盒子设置vertical-align:middle; text-align:center;
<style>
div {
display:table-cell;
vertical-align:middle;
text-align:center;
height: 400px;
width: 400px;
background-color: pink;
}
span {
display:inline-block;
width: 100px;
height: 100px;
background-color: purple;
}
</style>