flex
.parent {
height: 200px;
width: 200px;
display: flex;
justify-content: center;
align-items: center;
border: 1px solid red;
}
绝对定位
.parent {
height: 200px;
width: 200px;
position: relative;
border: 1px solid red;
}
.son {
height: 100px;
width: 100px;
position: absolute;
background-color: aqua;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
利用伪元素
.parent {
height: 200px;
width: 200px;
border: 1px solid forestgreen;
text-align: center; // 水平居中的关键属性
}
.son {
height: 100px;
width: 100px;
background-color: aquamarine;
display: inline-block;
vertical-align: middle;
}
.parent::before {
height: 100%; // 高度 100% 宽度 0
width: 0;
display: inline-block; // 内联块
content: '';
vertical-align: middle; // 内联块中线对齐
}
利用 margin: auto
.demo {
height: 20px;
width: 20px;
background-color: blue;
margin: auto;
}
.demo {
height: 20px;
width: 20px;
background-color: blue;
margin: auto;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}