1. 已知子元素宽高
-
绝对定位结合
calc()
.father { position: relative; } .son { position: absolute; left: calc(50% - 50px); top: calc(50% - 50px); }
-
绝对定位结合负
margin
.father { position: relative; } .son { position: absolute; width: 100px; height: 100px; left: 50%; top: 50%; margin-left: -50px; margin-top: -50px; }
2. 已知父元素高度
-
子元素设为inline-block,父元素设置text-align和line-height
.father { text-align: center; height: 500px; line-height: 500px; } .son { display: inline-block; }
3. 父元素和子元素宽高均未知
-
子元素边界为0,结合
margin: auto;
.father { position: relative; } .son { position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; }
-
绝对定位 + transfrom属性
.father { position: relative; } .son { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }
-
flex布局
.father { display: flex; justify-content: center; align-items: center; }
-
grid布局
// 1. 父类设置水平垂直居中 .father { display: grid; justify-items: center; align-items: center; } // 2. 子元素设置自身水平垂直居中 .father { display: grid; } .son { justify-self: center; align-self: center; }
4. 补充
其他的writing-mode、table布局等意义不大