使用 position: absolute 配合 top: 50% 和 transform: translate(-50%, -50%) 可实现元素在父容器中垂直水平居中,原理是通过绝对定位将元素左上角移至父容器中心,再利用 transform 将其自身宽高的一半反向偏移,使中心对齐,适用于子元素尺寸未知、响应式布局及兼容性要求高的场景,无需设置固定高度,代码简洁灵活。
要实现一个元素在父容器中垂直居中,使用 position: absolute 配合 top: 50% 和 transform: translate(-50%, -50%) 是一种非常灵活且兼容性良好的方法。这种方法不依赖于子元素的固定高度,适合响应式布局。
脱离文档流,其位置相对于最近的已定位祖先元素(即 position 为 relative、absolute 或 fixed 的父元素)进行偏移。居中内容
.container {
position: relative;
width: 300px;
height: 200px;
background-color: #f0f0f0;
margin: 50px auto;
}
.centered-box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 20px;
background-color: #007acc;
color: white;
text-align: center;
}
这里同时实现了水平和垂直居中:基本上就这些,掌握这个组合用法后,可以轻松应对大多数绝对定位下的居中需求。