开门见山
对子元素添加
{
left: 50%; // 设置左边距为父元素宽度的50%
transform: translateX(-50%); // 将元素向左移动该元素宽度的50%, 即使子元素的宽度大于父元素宽度,二者依然可以保持中心线对齐
}
示例
假设有这样的元素
<div class="parent">
<div class="child"></div>
</div>
css样式为
.parent {
position: relative; // 这里随意设置, 只要不是static就行
background-color: #00BCD4;
margin: 0 auto;
width: 100px;
height: 20px;
}
.child {
position: absolute;
background-color: #9e9e9e;
width: 150px;
height: 300px;
top: 20px;
left: 50%;
transform: translateX(-50%);
}