为了便于观察,我设置了基本样式
<div class="parent" id="parent">
<div class="child" id="child"></div>
</div>
#parent {
width: 500px;
height: 500px;
background-color: #eee;
}
#child {
width: 250px;
height: 250px;
background-color: red;
}
1. flex
.parent {
display: flex; // flex 自适应
align-items: center; // 垂直居中
justify-content: center; // 水平居中
}
.child {
}
2. inline-block
这个我不是很擅长
.parent {
}
.parent:before{
content: "";
height: 500px;
display: inline-block;
vertical-align: middle;
}
.child {
display: inline-block;
vertical-align: middle;
}
3. position
两种实现
偏移法:
.parent {
position: relative; // 父元素使用相对定位
}
.child {
position: absolute; // 子元素根据父元素进行绝对定位
top: 50%; // 距离顶部50% 父元素高度
left: 50%; // 距离左侧50% 父元素宽度
// 向上偏移子元素高度 50%
// 向左偏移子元素宽度 50%
translate: -50% -50%;
}
自动化:
.parent {
position: relative;
}
.child {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
}
4. grid
使用与 flex 相似
.parent {
display: grid;
justify-content:center;
align-items:center;
}
.child {
}
5. table-cell
.parent {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.child {
display: inline-block;
}