fixed位置偏移问题

元素的位置相对于浏览器窗口是固定位置,即使窗口是滚动的它也不会移动。

以上说的是正常情况。

还有一种特殊情况就是,当使用了fixed定位的元素的父元素使用了transform时,那么(猜测)fixed就会变成absolute定位,效果确实是这样的。

以下代码以供检验:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>fixed 位置偏移的问题</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.father {
width: 100vw;
height: 100vh;
background-color: red;
/* 父元素使用 transform ,把下面这行注释掉 fixed 就没问题了 */
transform: translate(25%, 25%);
/* margin: 25% 0 0 25%; */ /* 使用 margin 改变父元素的位置则不会影响 fixed 定位的效果 */
}
.child {
width: 50vw;
height: 50vh;
background-color: green;
position: fixed;
left: 25%;
top: 25%;
}
</style>
</head>
<body>
<div class="father">
<div class="child"></div>
</div>
</body>
</html>