总结的 11 种 CSS 水平垂直居中方式,不考虑兼容性。
1. 子元素相对父元素绝对定位,子元素 top,left 设置 50%,子元素 margin-top 和 margin-left 减去各自宽高的一半
.parent {
position: relative;
.children {
position: absolute;
width: 100px;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
}
2. 子元素相对父元素绝对定位,子元素 top,left 值为 50%,transform: translate(-50%,-50%)
.parent {
position: relative;
.children {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
}
3. 子元素相对父元素绝对定位,子元素上下左右全为 0,然后设置子元素 margin: auto;
.parent {
position: relative;
.children {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
}
4. 父元素设置表格布局,display: table-cell; vertical-align: middle,子元素设置 margin: auto;
.parent {
display: table-cell;
vertical-align: middle;
.children {
margin: auto;
}
}
5. 父元素设置弹性布局,display: flex; 子元素项设置 margin: auto;
.parent {
display: flex;
.children {
margin: auto;
}
}
6. 父元素设置弹性布局,display: flex; justify-content: center; align-items: center;
.parent {
display: flex;
justify-content: center;
align-items: center;
}
7. 父元素设置弹性布局,display: flex; place-content: center; place-items: center;
.parent {
display: flex;
place-content: center;
place-items: center;
}
8. 父元素设置网格布局,display: grid; 子元素项设置 margin: auto;
.parent {
display: grid;
.children {
margin: auto;
}
}
9. 父元素设置网格布局,display: grid; justify-content: center; align-items: center;
.parent {
display: grid;
justify-content: center;
align-items: center;
}
10. 父元素设置网格布局,display: grid; place-items: center;
.parent {
display: grid;
place-items: center;
}
11. 父元素设置网格布局,display: grid; place-content: center;
.parent {
display: grid;
place-content: center;
}
其实最常用的也就只有 1、2、3、6。