题例:
<body>
<div class="box" style="width: 500px;height: 500px;">
<div class="b" style="width: 100px;height: 100px;"><div>
</div>
</body>
1. 定位+自动外边距
.b{
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
margin:auto;
}
2. 定位+负值外边距反推 [需要知道目标元素的宽高]
.b{
position:absolute;
top:50%;
left:50%;
margin:(-50px 0 0 -50px)
[margin-top的数值为目标元素自身高度height负值的一半]
[margin-left的数值为目标元素自身宽度width负值的一半]
}
3. 定位+2d变换
.b{
position:absolute;
top:50%;
left:50%;
transform:translate(50% 50%)
}
4.弹性盒
.box{
display:flex;
justify-content:center;
align-items:center;
}
5.行内块属性
<body>
<div class="box" style="width: 500px;height: 500px;">
<div class="b" style="width: 100px;height: 100px;"><div>
<span></span>
[在父元素中添加空白文本]
</div>
</body>
.box{
line-height: 500px;
text-align: center;
}
.b{
display: inline-block;
vertical-align: middle;
}
6. 网格布局的grid-area属性
.box{
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-template-rows: 1fr 1fr 1fr;
grid-template-areas: '. . .'
'. a .'
'. . .';
}
.b{
grid-area: a;
}
7. 网格布局 [创造单个单元格]
.box{
display: grid;
grid-template-columns: 100px;
grid-template-rows: 100px;
justify-content: center;
align-content: center;
}