第一步
定位距离左侧(相对于浏览器)50%,此时盒子左侧是在浏览器中间的
position: fixed;
top: 0;
left: 50%;
显而易见这不是我们想要的效果,我们希望盒子的中线与处于浏览器正中间
第二步
//让盒子左移盒子的百分之五十
transform: translateX(-50%);
此时盒子就是居中对齐了
建议
在移动的时候最好设置为百分数,避免出现盒子大小改变的情况,设置为固定数值便不是居中对齐的效果了。
完整小栗子
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>小粉的移动</title>
<style>
.box {
position: fixed;
top: 0;
left: 50%;
width: 200px;
height: 200px;
//兼顾浏览器的兼容性
-webkit-transform: translateX(-50%);
transform: translateX(-50%);
background-color: pink;
}
</style>
</head>
<body>
<div class="box">
我是小粉
</div>
</body>
对于不了解transform属性的朋友这里送上贴心小链接:
https://www.w3school.com.cn/cssref/pr_transform.asp