失效的 position: fixed

position: fixed的作用是将元素相对于屏幕视口(viewport)的位置来指定其位置,在正常情况下其位置和父元素无关。如下图所示,父元素parent中有子元素child,子元素为position: fixed,相对浏览器窗口定位,不会随着滚动条滚动而改变滚动:

代码如下

 1 <!doctype html>
 2 <html>
 3 <head>
 4 <meta charset="utf-8">
 5 <title>position:fix 测试</title>
 6 <style>
 7     .parent{
 8         border: 1px red solid;
 9         height: 3000px;
10     }
11     .child{
12         width: 200px;
13         height: 200px;
14         position: fixed;
15         top: 100px;
16         left: 0;
17         background: green;
18     }
19 </style>
20 </head>
21 
22 <body>
23 <div class="parent">
24     <h2>parent</h2>
25     <div class="child">
26         <h3>child</h3>
27     </div>
28 </div>
29 </body>
30 </html>

而当父元素parent加上transform: translate(0, 0)样式的的时候,子元素的表现就像是相对于父元素parent的绝对定位一样,会随着滚动条而滚动,并与父元素的上边框保持100px。也就是说transform会使子元素中的固定定位失效。解决办法可以将子元素移到有transform属性的元素外边。

猜你喜欢

转载自www.cnblogs.com/lztl/p/9638262.html
今日推荐