- 方法1:display:flex+align-items
只需要给父元素设置属性
<style>
.box {
position: absolute;
width: 100px;
height: 100px;
border: 1px solid red;
display: flex;
justify-content: center;
align-items: center;
}
</style>
<div class="box">
<span>center</span>
</div>
.box {
position: relative;
width: 200px;
height: 200px;
border: 1px solid red;
}
.box span {
position: absolute;
top: 50%;
left: 50%;
margin-left: -25px;
margin-top: -25px;
text-align: center;
}
- 方法3:table-cell(只需要给父元素设置属性)
.box {
display: table-cell;
width: 100px;
height: 100px;
border: 1px solid red;
vertical-align: middle;
text-align: center;
}
- 方法4:绝对定位和 margin:auto和top,left,right,bottom都设置为0
(此时整个span元素都会居中,因为设置行高line-height和height相等,所以span元素内容居中)
.box span {
position: absolute;
width: 50%;
height: 50%;
border: 1px solid red;
position: absolute;
margin: auto;
overflow: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
text-align: center;
line-height: 473px;
}