今天遇到一个定位的问题,要让元素定位在浏览器的顶部,使用position: fixed居然没有效果,元素依然跟着浏览器滚动条走动,后来发现他的上层元素有的使用了transform: translate(0, 0);导致position: fixed功能失效了。所以特此记下来,当做一次小坑吧。
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>position:fixed无效</title>
<style>
body {
height: 20000px;
transform: translate(0, 0);
}
.box {
position: fixed;
width: 100px;
height: 100px;
background: red;
top: 300px;
}
</style>
</head>
<body>
<div class="box">固定定位元素</div>
</body>
</html>
滚动前

滚动后

所以,我们定位才会失效。当我们对上级元素设置transform: none;或者display:inline,就能解决这样的问题。下面是网上对定位写的不错的一篇帖子,给大家做个参考。
项目中遇到的小问题,position:fixed无效的一种情况
原文:https://www.cnblogs.com/xili95/p/8952560.html