# absolute + 负margin
<style>
.outer {
position: relative;
width: 300px;
height: 300px;
background: red;
}
.inner {
position: absolute;
width: 100px;
height: 100px;
background: yellow;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
</style>
<div class="outer">
<div class="inner">
12345
</div>
</div>
优点:
- 兼容性好
- 易于理解
缺点:
- 需要知道子元素的宽高
# absolute + auto margin
<style>
.outer {
position: relative;
width: 300px;
height: 300px;
background: red;
}
.inner {
position: absolute;
width: 200px;
height: 200px;
background: yellow;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
</style>
<div class="outer">
<div class="inner">
12345
</div>
</div>
优点:
- 易于理解
- 兼容性好
缺点:
- 需要知道子元素的宽高
# absolute + calc
.outer {
position: relative;
width: 300px;
height: 300px;
background: red;
}
.inner {
position: absolute;
width: 200px;
height: 200px;
background: yellow;
left: calc(50% - 100px);
right: calc(50% - 100px);
}
优点:
- 易于理解
缺点:
- 兼容性依赖于 calc,只支持 IE9及以上
- 需要知道子元素宽高
# absolute + transform
.outer {
position: relative;
width: 300px;
height: 300px;
background: red;
}
.inner {
position: absolute;
width: 200px;
height: 200px;
background: yellow;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
}
优点:
- 易于理解
- 实现简单
- 无需知道子元素宽高
缺点:
- 兼容性依赖于 transform,只支持 IE9 及以上
# table
.outer {
width: 300px;
height: 300px;
background: red;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.inner {
display: inline-block;
width: 200px;
height: 200px;
background: yellow;
}
优点:
- 兼容性好
- 易于实现
- 不需要知道子元素宽高
- 可读性强
# flex
.outer {
display: flex;
width: 300px;
height: 300px;
justify-content: center;
align-items: center;
background: red;
}
.inner {
width: 100px;
height: 100px;
background: yellow;
}
优点:
- 实现简单
缺点:
- 兼容性依赖于 flex
# grid
// 父元素指定子元素对齐方式
.outer {
display: grid;
align-content: center;
justify-content: center;
width: 300px;
height: 300px;
background: red;
}
.inner {
width: 200px;
height: 200px;
background: yellow;
}
// 子元素自己指定对齐方式
.outer {
display: grid;
width: 300px;
height: 300px;
background: red;
}
.inner {
width: 200px;
height: 200px;
align-self: center;
justify-self: center;
background: yellow;
}
优点:
- 实现简单
缺点:
- 兼容性依赖于 grid