推荐用transform实现绝对定位元素水平垂直居中:设position: absolute、top: 50%、left: 50%,再用transform: translate(-50%, -50%)反向偏移,无需知道宽高,兼容IE9+。
绝对定位元素水平垂直居中,核心是利用 top/left 定位 + transform 位移,这是最推荐、兼容性好且无需知道宽高的方法。
给元

position: absolute,再配合 top: 50% 和 left: 50% 将其左上角移到父容器中心,最后用 transform: translate(-50%, -50%) 向左上反向偏移自身宽高的一半。
示例代码:
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
margin 或预先知道尺寸当元素宽高固定时,可设 top: 50%、left: 50%,再通过负 margin 抵消自身一半尺寸。
例如宽 200px、高 100px 的元素:
.centered-fixed {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 100px;
margin-top: -50px; /* 高度一半 */
margin-left: -100px; /* 宽度一半 */
}
如果想避免 transform 或 margin,也可用 calc() 直接计算偏移位置,例如:
.centered-calc {
position: absolute;
top: calc(50% - 50px); /* 假设高 100px */
left: calc(50% - 100px); /* 假设宽 200px */
}
绝对定位元素的“居中”是相对于最近的 已定位祖先元素(即 position 为 relative、absolute、fixed 或 sticky)。若没有这样的祖先,默认相对于 。
position: relative 来建立定位上下文